HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Regex to enforce password requirements

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
regexenforcerequirementspassword

Problem

I'm trying to write regex to validate the password for the given rule.

Passwords must be at least 8 characters in length and contain at least 3 of the following 4 types of characters:

  • lower case letters (i.e. a-z)



  • upper case letters (i.e. A-Z)



  • numbers (i.e. 0-9)



  • special characters (e.g. !@#$&*)



I was going through this discussion and found this really great answer over there.

Now I'm trying to write regex for the mentioned requirements and I came up with the solution like this

^(?=.*[A-Z])(?=.*[!@#%%CODEBLOCK_0%%amp;*])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[!@#%%CODEBLOCK_0%%amp;*])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[!@#%%CODEBLOCK_0%%amp;*])(?=.*[a-z]).{8,}|
(?=.*[A-Z])(?=.*[!@#%%CODEBLOCK_0%%amp;*])(?=.*[0-9]).{8,}$


and it is working perfect see rubular but I want to optimize these regex and I'm not sure If there are any way to simplify this.
Any suggestion will be appreciated.

Solution

Split the regex into smaller parts to check each rule individually.

Here's the code for JavaScript. The same simple logic can be used for Ruby or any other language.

// Check the length
if (str.length >= 8 && validate()) {

}

// Check if all the characters are present in string
function validate(string) {
    // Initialize counter to zero
    var counter = 0;

    // On each test that is passed, increment the counter
    if (/[a-z]/.test(string)) {
        // If string contain at least one lowercase alphabet character
        counter++;
    }
    if (/[A-Z]/.test(string)) {
        counter++;
    }
    if (/[0-9]/.test(string)) {
        counter++;
    }
    if (/[!@#%%CODEBLOCK_0%%amp;*]/.test(string)) {
        counter++;
    }

    // Check if at least three rules are satisfied
    return counter >= 3;
}

Code Snippets

// Check the length
if (str.length >= 8 && validate()) {

}

// Check if all the characters are present in string
function validate(string) {
    // Initialize counter to zero
    var counter = 0;

    // On each test that is passed, increment the counter
    if (/[a-z]/.test(string)) {
        // If string contain at least one lowercase alphabet character
        counter++;
    }
    if (/[A-Z]/.test(string)) {
        counter++;
    }
    if (/[0-9]/.test(string)) {
        counter++;
    }
    if (/[!@#$&*]/.test(string)) {
        counter++;
    }

    // Check if at least three rules are satisfied
    return counter >= 3;
}

Context

StackExchange Code Review Q#136535, answer score: 20

Revisions (0)

No revisions yet.