Javascript Regular Expressions – Required field validation

javascriptvalidation

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

Best Solution

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