skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    • Match uppercase
    • Match lowercase
    • Match Numbers
    • Match special characters (specified between 9 and ])
    • Match any length and any combination.

    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,}$

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search