I know this has been asked before but all the answers I found didn’t work correctly on some cases.
I need to validate a password field and allow only certain characters.
The validation is done in both client and server side. On PHP I also couldn’t get the regex to perform as I needed, so what I did was split the password in an array of characters and check each one against an array of allowed chars. If any char is not on the array, it returns false.
The allowed characters are 0-9, a-z, A-Z and ` ! ” ? $ % ^ & * ( ) _ – + = { [ } ] : ; @ ~ # | < , > . ‘ / \ (whitespaces are not allowed).
Now I need something similar in Javascript and can’t figure how to do it.
Regex isn’t working correctly since it sometimes fails when there aren’t invalid characters (probably because of the chars order?).
The current regex I got from this site is
/^[A-Za-z\s`~!@#$%^&*()+={}|;:'",.<>\/?\\-]+$/
So, valid passwords could be, for example
urjv()$%...84
40#"!!mbn'"{}
890$%/\|`doc
,-=?wht(!{})=
Is there any other solution for this on JS, or is the regex wrong in fact?
Thanks for your help!
The following characters need to be escaped in a character class:
Note that the characters that need to be escaped are different when you’re creating a Regex object using
new.You are not escaping these characters when they are present, and some of them are not even included. Also, you’re including whitespace with the
\swhen you specified that it isn’t allowed. Finally, unless I looked at your regex too quickly, you did not include numbers. To address your concern that the order is what causes your regex to fail, order is not relevant in a character class.A corrected regex:
Here is a “test-suite”. I don’t claim it to be fool-proof but it seems to work fine:
http://jsfiddle.net/radu/AvGtY/
Change up the dictionary as needed and you should be good to go to test massive amounts of regexes. Note that as currently setup it only really checks consistency – that is, it only checks if the regex finds everything that is in the dictionary string.
Also, you need to check passwords server-side as well. Your client side code can be bypassed easily so you should always do validation server-side to prevent that. Client-side code is useful for immediate feedback but not much else in this case.
As pointed out by Qtax, the following would be a tad shorter and accomplish the same thing: