jQuery Validate plugin - password check - minimum requirements - Regex

You can create your own custom jQuery validation rule. which returns a valid message for all the conditions with 100% accuracy.

$.validator.addMethod("strong_password", function (value, element) {
    let password = value;
    if (!(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@#$%&])(.{8,20}$)/.test(password))) {
        return false;
    }
    return true;
}, function (value, element) {
    let password = $(element).val();
    if (!(/^(.{8,20}$)/.test(password))) {
        return 'Password must be between 8 to 20 characters long.';
    }
    else if (!(/^(?=.*[A-Z])/.test(password))) {
        return 'Password must contain at least one uppercase.';
    }
    else if (!(/^(?=.*[a-z])/.test(password))) {
        return 'Password must contain at least one lowercase.';
    }
    else if (!(/^(?=.*[0-9])/.test(password))) {
        return 'Password must contain at least one digit.';
    }
    else if (!(/^(?=.*[@#$%&])/.test(password))) {
        return "Password must contain special characters from @#$%&.";
    }
    return false;
});

Well you can use {8,} instead of "+" for a minimum of 8 chars with no maximum or better yet a {8, 20} for a minimum of 8 and a maximum of 20.

Really though I don't see the value in trying to squeeze all of your validation into a single regexp. If you break it up it makes it much easier to maintain, less bug prone, and it enables you to report back to the user the specific reason WHY the password failed instead of the entire requirement.

You could break it up into a few checks

//proper length
value.length >= 8 
//only allowed characters
/^[A-Za-z0-9\d=!\-@._*]+$/.test(value) 
//has a digit
/\d/.test(value)
//has a lowercase letter
/[a-z]/.test(value)

I'm not familiar with the jQuery Validation plugin, but I assume you could then return helpful a helpful message for each test that failed.


If I add (?=.*[a-z]) the whole code doesn't work anymore.

Add it here:

/^(?=.*[a-z])[A-Za-z0-9\d=!\-@._*]+$/

However, it's much easier to do this without a lookahead:

$.validator.addMethod("pwcheck", function(value) {
   return /^[A-Za-z0-9\d=!\-@._*]*$/.test(value) // consists of only these
       && /[a-z]/.test(value) // has a lowercase letter
       && /\d/.test(value) // has a digit
});