简体   繁体   中英

Adding minimum combination requirements on password policy

I need some help acquiring the right RegEx of the requirements to apply on password policy:

Match 3 out of 5 possible combinations of passwords that might contain minimum 1 uppercase, 1 lowercase, 1 number, 1 special character, 1 Unicode

Right now what I have is this combination

^(?=.*[az])(?=.*[AZ])(?=.*\d)[a-zA-Z\d,@#$%^&*()<>.,_\d\p{L}]{8,64}$

How do I apply the minimum 3 out of 5 possible combinations in the expression?

You can run a complex regex just like yours to check a password policy.

To count the individual rules you will need to write specific regex and test each one against your password.

Uppercase Regex Lowercase Regex Numeric Regex Special Regex

and count how many have passed at the end like 0/4 or 4/4.

You may write a helper method to validate the password. Something like the following should suffice:

static bool ValidPassword(string input)
{
    // TODO: Consider replacing this local variable with a static instance to
    //       initialize it only once.
    var checks = new List<Func<string, bool>>();
    checks.Add(s => Regex.IsMatch(s, @"[A-Z]"));
    checks.Add(s => Regex.IsMatch(s, @"[a-z]"));
    checks.Add(s => s.Any(c => char.IsDigit(c)));
    checks.Add(s => Regex.IsMatch(s, @"[!@#$%^&*()<>,._]"));
    // Used this instead of char.IsDigit (or just "\p{L}" to prevent English letters from
    // passing two checks. This will match any Unicode letter excluding English letters.
    checks.Add(s => Regex.IsMatch(s, @"[\p{L}-[A-Za-z]]"));

    int validChecksCount = 0;
    foreach(var check in checks)
    {
        if (check(input)) validChecksCount++;
        if (validChecksCount == 3) return true;
    }

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM