首先,我会阅读密码强度,并仔细检查您的政策,以确保您做的正确(我无法告诉你):
然后我会检查其他问题:
然后我开始做生意.
你可以使用Linq:
return password.Length >= z
&& password.Where(char.IsUpper).Count() >= x
&& password.Where(char.IsDigit).Count() >= y
;
Run Code Online (Sandbox Code Playgroud)
您也可以使用正则表达式(这可能是一个很好的选择,允许您将来插入更复杂的验证):
return password.Length >= z
&& new Regex("[A-Z]").Matches(password).Count >= x
&& new Regex("[0-9]").Matches(password).Count >= y
;
Run Code Online (Sandbox Code Playgroud)
或者你可以混合搭配它们.
如果必须多次执行此操作,则可以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);
Run Code Online (Sandbox Code Playgroud)
要计算大写字母和数字:
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++;
}
Run Code Online (Sandbox Code Playgroud)
并检查s.Length长度
祝好运!
| 归档时间: |
|
| 查看次数: |
5352 次 |
| 最近记录: |