Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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}))/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading