c#中密码验证的正则表达式

时间:2014-10-17 14:43:12

标签: c# regex

在c#

中需要有关正则表达式的密码验证帮助
  1. 8个字符的最小长度和16个
  2. 的最大值
  3. 至少一个数字,小写和一个uppper案例
  4. 我累了:

    var rule = new Regex("^(?=.{8,16}(?=*[a-z])(?=.*[A-Z])(?=.*[0-9])$");
    

    但它不起作用:(

3 个答案:

答案 0 :(得分:3)

你忘记了在第一个前瞻中关闭paranthesis。此外,您需要在所有前瞻后添加.*因为lookrounds是零宽度断言,它不会匹配任何字符,但仅断言是否可以匹配。

var rule = new Regex(@"^(?=.{8,16}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*$");

DEMO

答案 1 :(得分:0)

我喜欢尽可能避免使用正则表达式。我会做一些简单的测试:

 if (password.Length < 8 || password.Length > 16)
     result =  "Invalid Length";
 else if (!password.Any(char.IsDigit))
     result =  "Needs a digit";
 else if (!password.Any(char.IsLower))
     result =  "Needs a lowercase";
 else if (!password.Any(char.IsUpper))
     result =  "Needs an uppercase";
 else
     result = "Good password"; 

简单,干净,可读。您还可以向用户提供具体的反馈

答案 2 :(得分:0)

这是一种高级方法,可以清楚地返回输出错误消息

private bool ValidatePassword(string password, out string ErrorMessage)
{
    var input = password;
    ErrorMessage = string.Empty;

    if (string.IsNullOrWhiteSpace(input))
    {
        throw new Exception("Password should not be empty");
    }

    var hasNumber = new Regex(@"[0-9]+");
    var hasUpperChar = new Regex(@"[A-Z]+");
    var hasMiniMaxChars = new Regex(@".{8,15}");
    var hasLowerChar = new Regex(@"[a-z]+");
    var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");

    if (!hasLowerChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one lower case letter";
        return false;
    }
    else if (!hasUpperChar.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one upper case letter";
        return false;
    }
    else if (!hasMiniMaxChars.IsMatch(input))
    {
        ErrorMessage = "Password should not be less than or greater than 12 characters";
        return false;
    }
    else if (!hasNumber.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one numeric value";
        return false;
    }

    else if (!hasSymbols.IsMatch(input))
    {
        ErrorMessage = "Password should contain At least one special case characters";
        return false;
    }
    else
    {
        return true;
    }
}