Ashok
Ashok

Reputation: 175

Special character validation for password using regex

I am trying to create a regex for password validation with the following rules

  1. At least one upper case letter
  2. At least one lowercase letter
  3. At least one digit
  4. At least one among the allowed special characters
  5. Min 8 and max 30 chars

Created regex

^(?!.* )(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@"#%$&])(?=.{8,30})

This expression works fine for most of the scenarios except for special characters that are not allowed in list

For e.g. Password@*123 is showing as valid even though * is not in the allowed list. This is because it comes along with other special character that's in allowed list. The expression should not match if there's any special character that's outside the allowed list.

var pwd = "Password@*123";
var pwdRegex = /^(?!.* )(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@"#%$&])(?=.{8,30})/;
var result = pwdRegex .test(pwd);

Password@*123 - Showing as match even though * is not in allowed list

Upvotes: 1

Views: 274

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521997

One way to fix this would be to match, at the end of your current pattern, only characters which were logically whitelisted by one of the earlier positive lookaheads. Something like this:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@"#%$&])[A-Za-z0-9!@"#%$&]{8,30}$

Demo

Upvotes: 1

Related Questions