Regular Expression for password validation

^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$

---

^.*              : Start
(?=.{8,})        : Length
(?=.*[a-zA-Z])   : Letters
(?=.*\d)         : Digits
(?=.*[!#$%&? "]) : Special characters
.*$              : End

Password with the following conditions:

  1. At least 1 digit
  2. At least 2 special characters
  3. At least 1 alphabetic character
  4. No blank space

    'use strict';
    (function() {
        var foo = '3g^g$';
    
        console.log(/^(?=.*\d)(?=(.*\W){2})(?=.*[a-zA-Z])(?!.*\s).{1,15}$/.test(foo));
    
        /**
         * (?=.*\d)         should contain at least 1 digit
         * (?=(.*\W){2})    should contain at least 2 special characters
         * (?=.*[a-zA-Z])   should contain at least 1 alphabetic character
         * (?!.*\s)         should not contain any blank space
         */
    })();
    

Try this

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{6,20})

Description of above Regular Expression:

(           # Start of group
  (?=.*\d)      #   must contains one digit from 0-9
  (?=.*[a-z])       #   must contains one lowercase characters
  (?=.*[\W])        #   must contains at least one special character
              .     #     match anything with previous condition checking
                {8,20}  #        length at least 8 characters and maximum of 20 
)           # End of group

"/W" will increase the range of characters that can be used for password and pit can be more safe.


You can achieve each of the individual requirements easily enough (e.g. minimum 8 characters: .{8,} will match 8 or more characters).

To combine them you can use "positive lookahead" to apply multiple sub-expressions to the same content. Something like (?=.*\d.*).{8,} to match one (or more) digits with lookahead, and 8 or more characters.

So:

(?=.*\d.*)(?=.*[a-zA-Z].*)(?=.*[!#\$%&\?].*).{8,}

Remembering to escape meta-characters.

Tags:

C#

.Net

Regex