Regex to validate password strength

146,177

Solution 1

You can do these checks using positive look ahead assertions:

^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$

Rubular link

Explanation:

^                         Start anchor
(?=.*[A-Z].*[A-Z])        Ensure string has two uppercase letters.
(?=.*[!@#$&*])            Ensure string has one special case letter.
(?=.*[0-9].*[0-9])        Ensure string has two digits.
(?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
.{8}                      Ensure string is of length 8.
$                         End anchor.

Solution 2

You should also consider changing some of your rules to:

  1. Add more special characters i.e. %, ^, (, ), -, _, +, and period. I'm adding all the special characters that you missed above the number signs in US keyboards. Escape the ones regex uses.
  2. Make the password 8 or more characters. Not just a static number 8.

With the above improvements, and for more flexibility and readability, I would modify the regex to.

^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()\-__+.]){1,}).{8,}$

Basic Explanation

(?=(.*RULE){MIN_OCCURANCES,})     

Each rule block is shown by (?=(){}). The rule and number of occurrences can then be easily specified and tested separately, before getting combined

Detailed Explanation

^                               start anchor
(?=(.*[a-z]){3,})               lowercase letters. {3,} indicates that you want 3 of this group
(?=(.*[A-Z]){2,})               uppercase letters. {2,} indicates that you want 2 of this group
(?=(.*[0-9]){2,})               numbers. {2,} indicates that you want 2 of this group
(?=(.*[!@#$%^&*()\-__+.]){1,})  all the special characters in the [] fields. The ones used by regex are escaped by using the \ or the character itself. {1,} is redundant, but good practice, in case you change that to more than 1 in the future. Also keeps all the groups consistent
{8,}                            indicates that you want 8 or more
$                               end anchor

And lastly, for testing purposes here is a robulink with the above regex

Solution 3

You can use zero-length positive look-aheads to specify each of your constraints separately:

(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!@#$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})

If your regex engine doesn't support the \p notation and pure ASCII is enough, then you can replace \p{Lu} with [A-Z] and \p{Ll} with [a-z].

Solution 4

Answers given above are perfect but I suggest to use multiple smaller regex rather than a big one.
Splitting the long regex have some advantages:

  • easiness to write and read
  • easiness to debug
  • easiness to add/remove part of regex

Generally this approach keep code easily maintainable.

Having said that, I share a piece of code that I write in Swift as example:

struct RegExp {

    /**
     Check password complexity

     - parameter password:         password to test
     - parameter length:           password min length
     - parameter patternsToEscape: patterns that password must not contains
     - parameter caseSensitivty:   specify if password must conforms case sensitivity or not
     - parameter numericDigits:    specify if password must conforms contains numeric digits or not

     - returns: boolean that describes if password is valid or not
     */
    static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool {
        if (password.length < length) {
            return false
        }
        if caseSensitivty {
            let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0
            if !hasUpperCase {
                return false
            }
            let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0
            if !hasLowerCase {
                return false
            }
        }
        if numericDigits {
            let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0
            if !hasNumbers {
                return false
            }
        }
        if patternsToEscape.count > 0 {
            let passwordLowerCase = password.lowercaseString
            for pattern in patternsToEscape {
                let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0
                if hasMatchesWithPattern {
                    return false
                }
            }
        }
        return true
    }

    static func matchesForRegexInText(regex: String, text: String) -> [String] {
        do {
            let regex = try NSRegularExpression(pattern: regex, options: [])
            let nsString = text as NSString
            let results = regex.matchesInString(text,
                options: [], range: NSMakeRange(0, nsString.length))
            return results.map { nsString.substringWithRange($0.range)}
        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
}

Solution 5

I would suggest adding

(?!.*pass|.*word|.*1234|.*qwer|.*asdf) exclude common passwords
Share:
146,177

Related videos on Youtube

Ajay Kelkar
Author by

Ajay Kelkar

Updated on September 19, 2020

Comments

  • Ajay Kelkar
    Ajay Kelkar about 3 years

    My password strength criteria is as below :

    • 8 characters length
    • 2 letters in Upper Case
    • 1 Special Character (!@#$&*)
    • 2 numerals (0-9)
    • 3 letters in Lower Case

    Can somebody please give me regex for same. All conditions must be met by password .

    • Borealid
      Borealid over 12 years
      Are you really willing to trust your password security measures to the Internet at large?
    • Joachim Sauer
      Joachim Sauer over 12 years
      @Borealid: publishing your password policies should usually not significantly impact your security. If it does, then your policies are bad ("Only password and hello123 are valid passwords!").
    • Borealid
      Borealid over 12 years
      @Joachim Sauer: That's not what I meant. What I meant was that the poster is probably just going to trust whatever regex he receives. Not such a good idea.
    • Ajay Kelkar
      Ajay Kelkar over 12 years
      Actually this regex is going to be in service code , i will be testing for diff cases not blindly trust it :)
    • martinstoeckli
      martinstoeckli about 9 years
      Complex password rules will usually not lead to more safe passwords, important is only a minimum length. People cannot remember tons of strong passwords, and such rules can interfere with good password schemes. People can get very inventive to bypass such rules, e.g. by using weak passwords like "Password-2014". Often you end up with weaker passwords instead of stronger ones.
    • Jag
      Jag almost 8 years
      @martinstoeckli +1 Agreed. I've seen in the past strong password schemes and it's often led to weaker security due to people writing it down. Strong password schemes are fine with tech-savy users. LCDs (lowest common denominators ie normal people) need it kept simple. :)
    • ctwheels
      ctwheels over 5 years
      Password rules are old. Please see Reference - Password Validation for more information.
    • TRT 1968
      TRT 1968 over 1 year
      One definitely shouldn't trust password strength enforcement only to client-side processes, BUT a method of codifying requirements could be used as hints to password generators operating with the browser, such as Apple's Keychain. Form input fields already have a regex based PATTERN attribute, which can provide such hinting as well as giving client-side validation that would reduce server traffic.
  • NullUserException
    NullUserException about 11 years
    For anyone who wants a length of at least n, replace .{8} with .{n,}
  • Morvael
    Morvael almost 10 years
    +1 for a complete explanation. My password rules are different but based on your answer I can adapt the regex.
  • Admin
    Admin almost 10 years
    Thank you for describing whats happening in the regex. This serves as a great learning example for those of us who've never really got on with the syntax.
  • Nicholas Smith
    Nicholas Smith almost 10 years
    I also appreciate the explanation of the regex. To many times I use complex regex that I found, without really understanding what is going on.
  • AFract
    AFract about 8 years
    Positive look ahead is exactly the thing to use for this kind of things. Here's mine : ^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,24}$ (between 8 and 24 chars, at least one of each type among lowercase, uppercase, and numbers)
  • Necoras
    Necoras about 8 years
    @AFract Why have the 24 character limit? Why have any maximum length limit? Longer passwords add more entropy, and allow for things like pass phrases.
  • AFract
    AFract about 8 years
    @Necoras : 24 was just an example. It can easily be removed or changed in my regex. I shared it just because it's way simpler than the one in accepted answer, it enforces less constraints for end user which can also be an advantage in "real life" situation (even if accepted answer is perfectly answering to original question!). But you're right about max password length.
  • Mike
    Mike almost 8 years
    Don't forget that you may need to escape any of those special chars which might be interpreted as part of the regex (e.g. * - ? etc)
  • Gullbyrd
    Gullbyrd almost 8 years
    I would argue for separate regexes for each condition; that way you can inform the user of the nature of his shortcomings (you didn't include a capital letter, you need to include a numeral, etc.) Better than a generic "bad password" message followed by a recitation of the rules.
  • Pakk
    Pakk about 7 years
    This doesn't work: Allows '>' character at end of string if length is 8,20 regexstorm.net/tester?p=%5e(%3f%3d.*%5bA-Z%5d.*%5bA-Z%5d)(%3‌​f%3d.*%5b!%40%23%24%‌​26*%5d)(%3f%3d.*%5b0‌​-9%5d.*%5b0-9%5d)(%3‌​f%3d.*%5ba-z%5d.*%5b‌​a-z%5d.*%5ba-z%5d).%‌​7b8%2c20%7d%24&i=WWi‌​r11!!fd%3e
  • lospejos
    lospejos about 7 years
    Could you please check if is it correct? I'm in doubt because of opening round bracket in first line between triple doublequote and question mark. I can see that Python comment (hash) is later. I cannot see correspondent closing round bracket near end anchor (dollar sign). Should mention I'm not a regex profy.
  • ridgerunner
    ridgerunner over 6 years
    @lospejos - The # is not the start of a regular one line comment. This hash is part of a comment group which begins with a (?# and ends with a ). There are no unbalanced parens in this regex.
  • aKzenT
    aKzenT about 6 years
    Also, when using complex regex like above, it is very easy to open yourself to catastrophic backtracking (regular-expressions.info/catastrophic.html). This can go unnoticed until one day your server hangs with 100% CPU because a user used a "strange" password. Example: ^([a-z0-9]+){8,}$ (can you see the error?)
  • Ashish P
    Ashish P about 6 years
    for 1 upper case, 1 lower case , 1 numeral, 1 special character and min length of n characters:- ^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{n,}$ thanks a lot for the explanation
  • RockOnGom
    RockOnGom about 5 years
    Great pattern, I wonder why not using quantifiers? At least 1 special, 1 number, 1 special char, 8 character: ^(?=.*([A-Z]){1,})(?=.*[!@#$&*]{1,})(?=.*[0-9]{1,})(?=.*[a-z‌​]{1,}).{8,100}$
  • aloisdg
    aloisdg almost 5 years
    why not return preg_match("/^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^0-9]*[0-9]){2})‌​.{8,}$/", 'CaSu4Li8')?
  • Kumar Ashutosh
    Kumar Ashutosh over 4 years
    Starange that no one pointed that your answer accepts spaces too! Try increasing the accepted chars from 8 to 9 and add a space.
  • Toto
    Toto almost 4 years
    Your regex is matching 12345678 are you sure it is a strong password? Please, try your regex before posting.
  • Toto
    Toto almost 4 years
    That's better but doesn't answer the question, they want 1) 8 characters length. 2) 2 letters in Upper Case. 3) 1 Special Character (!@#$&*). 4) 2 numerals (0-9). 5) 3 letters in Lower Case.
  • Juned Khatri
    Juned Khatri almost 4 years
    @Toto Can you please share your thoughts now?
  • Toto
    Toto almost 4 years
    Your regex doesn't take into account that the 2 mandatory Uppercase letters could be separated with other characters, same remark for lowercase and digits. The valid answer is the one that has been accepted.
  • lsu_guy
    lsu_guy over 3 years
    Thanks @AFract. I'm using it in my code. I like readability and repeat-ability, for when you have to go back and change it in the future i.e. in case of a password policy change :)
  • QMaster
    QMaster about 3 years
    @RockOnGom I think your suggestion is more proper because of flexibility. That is great but how can I do to avoid accepting SPACE in the string?
  • QMaster
    QMaster about 3 years
    I think this is proper for most cases: ^(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[0-9]{1,})(?=.*[~!@#$%^&‌​*()\-_=+{};:,<.>]{1,‌​}).{8,}$
  • RockOnGom
    RockOnGom about 3 years
    @QMaster: I think that can work, but not sure about it's performance: ^(?=.*([A-Z]){1,})(?=.*[!@#$&*]{1,})(?=.*[0-9]{1,})(?=.*[a-z‌​]{1,})([^ ]){8,100}$
  • QMaster
    QMaster about 3 years
    @RockOnGom That does not work. Thanks anyway. I will be working on it. I'll appreciate if you share new results.
  • Mohamed Wagih
    Mohamed Wagih about 3 years
    Fantastic explanation.This should be the accepted answer IMHO.
  • J.Joe
    J.Joe about 3 years
    /^(?=.*[a-z]){3,}(?=.*[A-Z]){2,}(?=.*[0-9]){2,}(?=.*[!@#$%^&‌​*()--__+.]){1,}.{8,}‌​$/.test("aA1$bcde") return true with just 1 numeric and 1 capital
  • lsu_guy
    lsu_guy about 3 years
    Updated to include your test case @PriyankBolia. See new robulink, which should now work.
  • ennth
    ennth about 3 years
    @Isu_guy what about if you want it to FAIL if there if it exceeds Max occurances? is it just {min_occurances, max_occurances} ???
  • ennth
    ennth about 3 years
    how do you do this but with a max range? so like two capital letters but NO MORE than two capital letters? or two numeric digits but NO MORE than two???
  • lsu_guy
    lsu_guy about 3 years
    correct. It should be {min_occurances, max_occurances}. Keep in mind, I haven't tested that, so please do so. Also haven't seen password policies where a max is specified. Could you share the use-case, which requires a max. Thanks.
  • Newton Suhail
    Newton Suhail almost 2 years
    Thanks, you made it simple and easy to understand. I changed as per my requirement easily
  • Fre Timmerman
    Fre Timmerman over 1 year
    I see loads of ^ start and $ end anchors used with these positive lookahead. why are those needed? in my testing i can leave those out
  • Mahdi mehrabi
    Mahdi mehrabi over 1 year
    I think this is the right way