asp.netregexreg-expressionvalidator

asp.net 4.0 regularExpressionValidator


I need to modify my regularexpressionvalidator code to require the user to meet the following password requirements:

a. Contains at least 2 uppercase characters: A, B, C etc.

b. Contains at least 2 lowercase characters: a, b, c, etc.

c. Contains at least 2 numbers: 1,2,3,4,5,6,7,8,9,0

d. Contains at least 2 special characters, i.e.

! @ # $ % ^ & * ( ) _ + | ~ - = \ ` { } [ ] : " ; ' < > ? , . /

Current code only requires a 10 character password length:

<asp:RegularExpressionValidator ID="valPassword" 
runat="server" ControlToValidate="txtPassword" 
ErrorMessage="Error: 10 character required password length"
ValidationExpression=".{10}.*" /> 

Solution

  • You can use this regex

    ^(?=^.{10}$)(?=^(.*?[A-Z]){2,}.*?$)(?=^(.*?[a-z]){2,}.*?$)(?=^(.*?\d){2,}.*?$)(?=^(.*?[!@#$%^&]){2,}.*?$).*?$
       --------  ---------------------  --------------------- ------------------- --------------------------
          |               |                       |                    |                      |->checks for 2 or more special characters
          |               |                       |                    |->checks for 2 or more digits 
          |               |                       |->checks for 2 or more small letters
          |               |->checks for 2 or more capital words
          |
          |->checks for 10 words..