Jonas
Jonas

Reputation: 311

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?

Upvotes: 0

Views: 6647

Answers (1)

ruakh
ruakh

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:

  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}$/;

Upvotes: 1

Related Questions