Reputation: 91
I am working on this code and using "match" function to detect strength of password. how can I detect if string has special characters in it?
if(password.match(/[a-z]+/)) score++;
if(password.match(/[A-Z]+/)) score++;
if(password.match(/[0-9]+/)) score++;
Upvotes: 4
Views: 29014
Reputation: 49
/[^a-zA-Z0-9 ]+/ This will accept only special characters and will not accept a to z & A to Z 0 to 9 digits
Upvotes: 0
Reputation: 238
As it look from your regex, you are calling everything except for alphanumeric a special character. If that is the case, simply do.
if(password.match(/[\W]/)) {
// Contains special character.
}
Anyhow how why don't you combine those three regex into one.
if(password.match(/[\w]+/gi)) {
// Do your stuff.
}
Upvotes: 1
Reputation: 2114
You'll have to whitelist them individually, like so:
if(password.match(/[`~!@#\$%\^&\*\(\)\-=_+\\\[\]{}/\?,\.\<\> ...
and so on. Note that you'll have to escape regex control characters with a \
.
While less elegant than /[^A-Za-z0-9]+/
, this will avoid internationalization issues (e.g., will not automatically whitelist Far Eastern Language characters such as Chinese or Japanese).
Upvotes: 4
Reputation: 18773
you can always negate the character class:
if(password.match(/[^a-z\d]+/i)) {
// password contains characters that are *not*
// a-z, A-Z or 0-9
}
However, I'd suggest using a ready-made script. With the code above, you could just type a bunch of spaces, and get a better score.
Upvotes: 2
Reputation: 41934
If you mean !@#$% and ë as special character you can use:
/[^a-zA-Z ]+/
The ^
means if it is not something like a-z or A-Z or a space.
And if you mean only things like !@$&$ use:
/\W+/
\w
matches word characters, \W
matching not word characters.
Upvotes: 12
Reputation: 22007
if(password.match(/[^\w\s]/)) score++;
This will match anything that is not alphanumeric or blank space. If whitespaces should match too, just use /[^\w]/
.
Upvotes: 1
Reputation: 120188
Just do what you did above, but create a group for !@#$%^&*()
etc. Just be sure to escape characters that have meaning in regex, like ^
and (
etc....
EDIT -- I just found this which lists characters that have meaning in regex.
Upvotes: 1