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?
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}$/;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.