2

Form field is message. I don't want users to be able to send only spaces as a message. So,

" " and "   " and "         " and "                   " and so on will go to something like

if (x==null || x=="" || x==" " || x=="  ") {
    alert("At least 8 characters are required!");
    return false;
}    

but I need to arrange the 'if' area in a way that it will not accept only 'space' character, no matter how many 'space' characters the user puts (And at least total of , let's say, eight characters need to be put).

Thank you.

1
  • 1
    Use regular expressions. In many languages \s matches any "white space" characters. Commented Jul 9, 2014 at 0:36

2 Answers 2

3

Just so you know, there are many ways to do this, but I'll give you a fairly simple one.

Use .trim() to remove all whitespace:

if(x.trim() === "" || x === null){
  alert("At least 8 characters are required!");
  return false;
}

Demo

Alternatively, you could remove the space characters like this:

x = x.split(" ").join("");
if(x === "" || x === null){
  alert("At least 8 characters are required!");
  return false;
}

Demo

If neither of those work for you, try RegEx.

Sign up to request clarification or add additional context in comments.

Comments

0

trim() eliminates all spaces, so try

if (x===null || x.trim() === "") {
    alert("At least 8 characters are required!");
    return false;
}

2 Comments

Thanks. x.trim() != "" or x.trim() === "" ?
@IMayNeed Thanks for the notice. I'm usually not that oblivious :P

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.