Reputation: 311
I have constructed the following Regex, which allows strings that only satisfy all three conditions:
The Regex is:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]$"
I use the following Javascript code to verify input:
var regPassword = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]$");
regPassword.test(form.passwordField.value);
The test()
method returns false
for such inputs as abc123!ZXCBN
. I have tried to locate the problem in the Regex without any success. What causes the Regex validation to fail?
Upvotes: 0
Views: 6647
Reputation: 183584
I see two major problems. One is that inside a string "..."
, backslashes \
have a special meaning, independent of their special meaning inside a regex. In particular, \d
ends up just becoming d
— not what you want. The best fix for that is to use the /.../
notation instead of new RegExp("...")
:
var regPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]$/;
The other problem is that your regex doesn't match your requirements.
Actually, the requirements that you've stated don't really make sense, but I'm guessing you want something like this:
$@$!%*?&
.$@$!%*?&
.If so, then you've managed #1 and #2, but forgot about #3. Right now your regex demands that the length be exactly 1. To fix this, you need to add {8,20}
after the [A-Za-z\d$@$!%*?&]
part:
var regPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,20}$/;
Upvotes: 1