如何validation密码是否包含X大写字母和Y数字?
如何在C#中validation密码至少包含X个大写字母和至少Y个数字,整个字符串是否长于Z?
谢谢。
密码强度:
首先,我会阅读密码强度,并仔细检查您的政策,以确保您做的正确(我无法告诉你):
- http://en.wikipedia.org/wiki/Password_strength
- https://www.grc.com/haystack.htm
- http://xkcd.com/936/ (一个笑话,但很好的思考)
然后我会检查其他问题:
- 创建正则表达式以检查强密码
- 密码强度
然后我开始做生意。
执行:
你可以使用Linq:
return password.Length >= z && password.Where(char.IsUpper).Count() >= x && password.Where(char.IsDigit).Count() >= y ;
您也可以使用正则表达式(这可能是一个很好的选择,允许您将来插入更复杂的validation):
return password.Length >= z && new Regex("[AZ]").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("[AZ]"); private Regex digitsMatcher = new Regex("[az]"); } var validator = new PasswordValidator() { FewestUppercaseCharactersAllowed = x, FewestDigitsAllowed = y, MinimumLength = z, }; return validator.IsValid(password);
要计算大写字母和数字:
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
的长度
祝好运!
使用LINQ Where()方法简洁明了:
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;
这应该这样做:
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; }