Regex for strong password in ASP.net

坚强是说给别人听的谎言 提交于 2019-12-13 14:31:22

问题


I need to check for a password containing 3 of the following 4:

  1. Lowercase letter
  2. Uppercase letter
  3. Numeric character
  4. Special characters (like %, $, #, ...)

The length of the password has to be between 6 and 20 characters. I currently have this:

public void ChangePassword(string password)
    {

        Regex regex1 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]){6,20}$");
        Regex regex2 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*?[#?!@$%^&*-]){6,20}$");
        Regex regex3 = new Regex("^(?=.*[0-9])(?=.*[A-Z])(?=.*?[#?!@$%^&*-]){6,20}$");
        Regex regex4 = new Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*?[#?!@$%^&*-]){6,20}$");
        Regex regex5 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*?[#?!@$%^&*-]){6,20}$");

        Match match1 = regex1.Match(password);
        Match match2 = regex2.Match(password);
        Match match3 = regex3.Match(password);
        Match match4 = regex4.Match(password);
        Match match5 = regex5.Match(password);

        if (match1.Success || match2.Success || match3.Success ||
            match4.Success || match5.Success)
        {

            Password = password;

        }
        else
        {
            throw new PasswordNotGoodException();
        }
    }

However, this doesn't match anything at all. It's for a school project, so I really could use some help.


回答1:


Instead of REGEX you can use:

string password = "aA1%";
HashSet<char> specialCharacters = new HashSet<char>() { '%', '$', '#' };
if (password.Any(char.IsLower) && //Lower case 
     password.Any(char.IsUpper) &&
     password.Any(char.IsDigit) &&
     password.Any(specialCharacters.Contains))
{
  //valid password
}

Much simpler and clean.

EDIT:

If you need at least 3 out of these 4 conditions to be true you can do:

int conditionsCount = 0;
if (password.Any(char.IsLower))
    conditionsCount++;
if (password.Any(char.IsUpper))
    conditionsCount++;
if (password.Any(char.IsDigit))
    conditionsCount++;
if (password.Any(specialCharacters.Contains))
    conditionsCount++;

if (conditionsCount >= 3)
{
    //valid password
}



回答2:


The last repetition is wrong here:

Regex regex1 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]){6,20}$");

do instead:

Regex regex1 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,20}$");
//                                   notice the dot here ___^

And it's the same for all your regex.



来源:https://stackoverflow.com/questions/22232582/regex-for-strong-password-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!