I am trying to create a regex for accepting uppercase, lowercase letters, numbers and only mentioned special characters for creating password. What I have built works fine, however, when I add a special character mentioned and one which is not in the list, it is still accepted.
What I have built:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%&*])(?=.{8,})
What happens here is that when I enter # it works. When I enter # AND +, it still accepts. I need it to fail and only allow characters mentioned. If the user enters one which is not mentioned, it should fail
2
Answers
I believe the regex you are looking for is
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%&*])[A-Za-z0-9!@#$%&*]{8,}$
In this regex,
[A-Za-z0-9!@#$%&*]
is a character class that matches any uppercase letter, lowercase letter, digit, or one of the specified special characters. By including this character class in the main pattern and ensuring that it matches the entire password string from start to end, the regex will reject any passwords that contain special characters not explicitly mentioned.This should work:
^[a-zA-Z0-9!@#$%&*]+$
The key here is the
+
at the end. It allows unlimited characters from the specified set to be included in the match.This set will:
9
and]
)I’d maybe suggest using alternative requirements though. This is the regex I use for passwords. It requires a minimum of 8 characters, one upper, one lower, one number, and one symbol (of any kind).
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^ws]).{8,}$