Home > other >  Check is string contains special characters and at least 2 characters amongs digit and letter
Check is string contains special characters and at least 2 characters amongs digit and letter

Time:04-10

Hi guys I trying to check if password contains special caracters and at least 2 characters (digit or letter) So like this:

("&#€$&&÷") ====> false

("&#&'&*#5") ====> false

(">~<<`<•5t") ====> true

("{\><>\tt") =====> true

("65%#^$*@") ====> true

("7373673") ====> false

("7267373~") ====> true

I've tried this regular expression but It seems not working:

/^((?=.*\d{2})|(?=.*?[a-zA-Z]{2}))/

CodePudding user response:

You can assert the 2 occurrences of a character or digit in the same lookahead, and then match at least a single "special" character.

Using a case insensitive pattern:

^(?=(?:[^a-z\d\n]*[a-z\d]){2})[a-z\d]*[~!@#$%^&*()_ <>•`{}\\][~!@#$%^&*()_ <>•`{}\\a-z\d]*$

The pattern matches:

  • ^ Start of string
  • (?:[^a-z\d\n]*[a-z\d]){2} Assert 2 occurrences of either a char a-z or a digit. The [^a-z\d\n]* part negates the character class using [^ to prevent unnecessary backtracking
  • [a-z\d]* Match optional chars a-z or a digit
  • [~!@#$%^&*()_ <>•`{}\] Match a special character
  • [~!@#$%^&()_ <>•`{}\a-z\d] Match optional allowed chars
  • $ End of string

Regex demo

  • Related