Pravin Deshmukh Pravin Deshmukh - 11 days ago 6
C# Question

RegEx for validating password

I have a requirement to validate password using regular expression
and below is the validation criteria

Password should contain any 3 out of the 4 types of character:


  1. Lower case letters (a,b,c,d,.......,y,z)

  2. Upper case letters (A,B,C,D,......,Y,Z)

  3. Numerals (0,1,2,3,4,5,6,7,8,9)

  4. Special characters ($,&,%,!,#,@)"



I have come up with below regex, but the problem is it only validates till first 9 characters and allows any character after words

^(?=.{9,})((?=.*\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*\d)(?=.*[a-z])(?=.*[!@#$%&])|(?=.*\d)(?=.*[A-Z])(?=.*[!@#$%&])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&])).*$


EDIT : I have gone through similar questions, but my question is different because it expects 3 out of 4 criteria to be satisfied and with only limited set of characters.

Any help would be appreciated!

Answer

Replace your final "is made of characters" check

.*$

with a check for "is made of only allowed characters"

[A-Za-z0-9$&%!#@]*$

The former allows you to use any character you want as long as the other rules are satisfied; the latter ensures every character in the input is one of the allowed characters.

Comments