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
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
3 Comments
Tomalak
test() is on the RegExp object: "/\S/.test(myField.value)"
nickf
ya, i always get those two mixed up.
Tomalak
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.
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
Tomalak
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.
Geo
I know . This will work in 2 ways : you test the /^\s+/ for matching , or you test the /^\S+/ for non-matching .
Tomalak
Hm, I did not think of the "non match" logic. Nice catch.
Tomalak
Nevertheless this is non-obvious, you should make the distinction clearer in your answer.
nickf
/^\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!