【发布时间】:2012-01-14 22:03:48
【问题描述】:
如何在 C# 中验证密码至少包含 X 个大写字母和至少 Y 个数字,并且整个字符串比 Z 长?
谢谢。
【问题讨论】:
-
我可能会使用一些标准的密码验证规则,可能与 RegEx 一起使用,而不是逐字符解析...请参阅这个:stackoverflow.com/questions/1152872/…
标签: c# string-matching
如何在 C# 中验证密码至少包含 X 个大写字母和至少 Y 个数字,并且整个字符串比 Z 长?
谢谢。
【问题讨论】:
标签: c# string-matching
计算大写字母和数字:
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:
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);
【讨论】:
使用 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;
【讨论】:
应该这样做:
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;
}
【讨论】: