9

How do I check if a field (textbox) is empty or filled only with white spaces (spaces/enters/tabs etc.), using javascript RegExp?

3 Answers 3

15
if (myField.value.match(/\S/)) {
  // field is not empty
}
// or
if (/\S/.test(myField.value)) {
  // field is not empty
}

Explanation, since other people seem to have some crazy different ideas:

\s will match a space, tab or new line.
\S will match anything but a space, tab or new line.
If your string has a single character which is not a space, tab or new line, then it's not empty.
Therefore you just need to search for one character: \S

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

3 Comments

test() is on the RegExp object: "/\S/.test(myField.value)"
ya, i always get those two mixed up.
I like the simplicity of the approach. But I don't think negated negative logic ("if not value contains non-space chars") contributes a lot to code comprehensibility.
5
/^\s*$/.test(string)

Could be used like so:

var empty_string = /^\s*$/; //create RegExp object for re-use

if (empty_string.test(myFormField.value))
{
  alert("Please be a bit more elaborate!");
}

Comments

1

By testing for

/\s/ or /\S/
you will only be testing for one character . So , it will be better to test instead for :

/^\s+$/ or /^\S+$/

EDIT: please note that or is not part of the code .

EDIT2:

The test for matching :


if(string.match(/^\s+$/)) {
   alert("string is empty!");
}

And the test for non-matching :


if(!string.match(/^\S+$/)) {
   alert("string is empty!");
}

You could use either of these to same result .

5 Comments

The latter will fail for the empty string. I am relatively sure the question author wants to include that as well. And why do you use "\S"? It will match anything but whitespace, so it's wrong here.
I know . This will work in 2 ways : you test the /^\s+/ for matching , or you test the /^\S+/ for non-matching .
Hm, I did not think of the "non match" logic. Nice catch.
Nevertheless this is non-obvious, you should make the distinction clearer in your answer.
/^\S+$/ will give you a false positive on the input: "This is not empty". /^\s+$/ will give you a false negative on the input: "". If you find any ONE character which is not \s (ie: \S), then it's not empty. it's very simple!

Your Answer

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