简体   繁体   中英

Regex allowing only alphanumeric and special characters does not work

I have constructed the following Regex, which allows strings that only satisfy all three conditions:

  1. Allows alphanumeric characters.
  2. Allows special characters defined in the Regex.
  3. String length must be min 8 and max 20 characters.

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:

  1. Must contain at least one lowercase letter, at least one uppercase letter, at least one digit, and at least one of the special characters $@$!%*?& .
  2. Can only contain lowercase letters, uppercase letters, digits, and the special characters $@$!%*?& .
  3. Total length must be between 8 and 20 characters, inclusive.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM