Reputation: 3438
I'm using https://regexr.com/ to test a regular expression. I'm trying to validate a name input on a form, so:
In my validation function, I can have:
if (/\d/.test(charStr)) {
return false;
}
/\d/
will match numbers. So far, so good.
Changing it to:
if (/\d|\W/.test(charStr)) {
return false;
}
..will match numbers \d
or |
non-word characters \W
, which is good, except that it's also matching whitespace characters like space and backspace.
So, I'm trying to somehow use \W
, but with the exception of whitespace characters.
I tried:
if (/\d|\W[^\s]/.test(charStr)) {
return false;
}
So, match numbers \d
, or non-word characters \W
excepting whitespace characters [^\s]
, but my syntax appears to be wrong here.
What am I doing wrong? Thanks.
Upvotes: 0
Views: 1857
Reputation: 214959
In regexes, whitelisting (telling the engine what you want) is usually much easier than blacklisting (telling what you don't want). If you only want letters and spaces, just say so:
/^[a-z ]+$/
Note that you have to trim
the input before using that, otherwise it will "validate" a string consisting entirely of spaces.
Upvotes: 3