【问题标题】:How to verify that the password contains X uppercase letters and Y numbers?如何验证密码是否包含 X 大写字母和 Y 数字?
【发布时间】:2012-01-14 22:03:48
【问题描述】:

如何在 C# 中验证密码至少包含 X 个大写字母和至少 Y 个数字,并且整个字符串比 Z 长?

谢谢。

【问题讨论】:

标签: c# string-matching


【解决方案1】:

计算大写字母和数字:

string s = "some-password";
int upcaseCount= 0;
int numbersCount= 0;
for (int i = 0; i < s.Length; i++)
{
    if (char.IsUpper(s[i])) upcaseCount++; 
    if (char.IsDigit(s[i])) numbersCount++;
}

并检查s.Length 的长度

祝你好运!

【讨论】:

    【解决方案2】:

    密码强度:

    首先,我会阅读密码强度,并仔细检查您的政策以确保您所做的事情是正确的(我无法立即告诉您):

    然后我会检查其他问题:

    那我就说正事了。

    实施:

    你可以使用 Linq:

    return password.Length >= z
        && password.Where(char.IsUpper).Count() >= x
        && password.Where(char.IsDigit).Count() >= y
        ;
    

    您也可以使用正则表达式(这可能是一个不错的选择,可以让您在未来插入更复杂的验证):

    return password.Length >= z
        && new Regex("[A-Z]").Matches(password).Count >= x
        && new Regex("[0-9]").Matches(password).Count >= y
        ;
    

    或者你可以混合搭配。

    如果您必须多次执行此操作,您可以通过构建一个类来重用 Regex 实例:

    public class PasswordValidator
    {
        public bool IsValid(string password)
        {
            return password.Length > MinimumLength
                && uppercaseCharacterMatcher.Matches(password).Count
                    >= FewestUppercaseCharactersAllowed
                && digitsMatcher.Matches(password).Count >= FewestDigitsAllowed
                ;
        }
    
        public int FewestUppercaseCharactersAllowed { get; set; }
        public int FewestDigitsAllowed { get; set; }
        public int MinimumLength { get; set; }
    
        private Regex uppercaseCharacterMatcher = new Regex("[A-Z]");
        private Regex digitsMatcher = new Regex("[a-z]");
    }
    
    var validator = new PasswordValidator()
    {
        FewestUppercaseCharactersAllowed = x,
        FewestDigitsAllowed = y,
        MinimumLength = z,
    };
    
    return validator.IsValid(password);
    

    【讨论】:

    • @SaiKalyanAkshinthala:现已修复。我在扩展答案时看到了我的错误:)
    【解决方案3】:

    使用 LINQ 简洁明了 Where() method:

    int requiredDigits = 5;
    int requiredUppercase = 5;
    string password = "SomE TrickY PassworD 12345";
    
    bool isValid = password.Where(Char.IsDigit).Count() >= requiredDigits
                   && 
                   password.Where(Char.IsUpper).Count() >= requiredUppercase;
    

    【讨论】:

      【解决方案4】:

      应该这样做:

      public bool CheckPasswordStrength(string password, int x, int y, int z)
      {
         return password.Length >= z &&
                password.Count(c => c.IsUpper(c)) >= x &&
                password.Count(c => c.IsDigit(c)) >= y;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-14
        • 2020-05-16
        • 2018-01-02
        • 2017-08-11
        • 2016-07-05
        • 1970-01-01
        • 2012-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多