views:

4180

answers:

4

Hello,

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

+5  A: 
 if (myField.value.match(/\S/)) {
    // 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

nickf
test() is on the RegExp object: "/\S/.test(myField.value)"
Tomalak
ya, i always get those two mixed up.
nickf
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.
Tomalak
+1  A: 

See answers to a similar question: recommendation for javascript form validation library.

gimel
he wasn't asking for a library - just a regex.
nickf
+3  A: 
/^\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!");
}
Tomalak
A: 
Geo
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.
Tomalak
I know . This will work in 2 ways : you test the /^\s+/ for matching , or you test the /^\S+/ for non-matching .
Geo
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.
Tomalak
/^\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!
nickf