I’m trying to do a password validation regex, it must ask for an upper case, a lower case, a special character, a number, and to not have any white spaces, so I implemented the following RegEx:
/^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[.!@#$%^&*])[^s][a-zA-Z0-9.!@#$%^&*][^s]{8,16}$/
But I need to put more than 8 characters to work for some reason.
I typed my password as: Yama#892
Which is supposed to be 8 characters but Regex didn’t accept it until I type it like this for example: Yama###892
If I’m correct those are 10 characters.
So do some characters not count towards quantifier? If not how do I count for all 8 characters?
This is how my code looks:
//...
const PASSWORD_REGEX =
"^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[.!@#$%^&*])[^\s][a-zA-Z0-9.!@#$%^&*][^\s]{8,16}$";
if (password && !password.match(PASSWORD_REGEX)) {
errors["password"] = "Password is invalid.";
}
//...
2
Answers
ignoring the lookaheads, it says:
Remove
[s]
-s (S
is equivalent to them btw) ant it’ll work fine(you don’t need whitespace check
(?!.*s)
as you limit chars in[a-zA-Z0-9.!@#$%^&*]
)@Dimava‘s answer already explained why your initial Regex isn’t accepting passwords with 8 characters.
You can find a cleaned up, working version of your code bellow:
Improvements:
d
for digits.[^ws]
non-alphanumeric character.test
instead ofmatch
as we don’t need to extract the password..{8,16}
for the password length instead of having to restrict valid characters.