0

I am having a script which validates a user's name. When the user enters name without spaces then it works fine. If user enters name with spaces (name, surname, lastname etc) then it is not working. I am trying to capture 'space' character using \s but it is not working.

My script is:

var name=document.forms["newform"]["fullname"].value; //get the name from HTML form
var charpos = name.search("[^A-Za-z\s]");
if (name.length <= 0 || name.length>=50 || charpos >= 0)
{
    alert('wrong.');
}
else
{
     alert('correct');
}

Input1: AFGH

Output1: correct

Input2: ABCD EFGH

Output2: wrong

When Input2 is given, charpos gets the value '5'.

1 Answer 1

1

The string literal is swallowing the \.

You should use a regex literal:

name.search(/[^A-Za-z\s]/);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks SLaks. It worked!! Can you please explain a little how string literal is swallowing the ` \ `? What swallowing means? Thanks again.
@iSumitG, \ is an escape in regular strings, if you want the character it self to be present in the string, you have to escape it, eg "[^A-Za-z\\s]".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.