我不能告诉你我有多么讨厌强加密码限制,但唉,我的老板强制要求。我需要一个满足以下条件的正则表达式:
这是我到目前为止所得到的,但它似乎只满足一个条件:
[RegularExpression(@"^(?=.{8})(?=.*[^a-zA-Z])", ErrorMessage = "Password must contain at least 8 characters, a mix of uppercase and lowercase, and 2 numbers.")]
[DataType(DataType.Password)]
public string Password { get; set; }
答案 0 :(得分:2)
仅使用前瞻(?=)
,Perl语法:
^(?=.{8})(?=.*[a-z])(?=.*[A-Z])(?=.*\d.*\d)
答案 1 :(得分:0)
使用自定义属性的一种方法:
public class CustomPasswordAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var password = value.ToString();
if (password.Length < 8)
return new ValidationResult(ErrorMessage);
var hasUpperCase = false;
var hasLowerCase = false;
var numDigits = 0;
foreach (var c in password)
{
if (char.IsUpper(c))
hasUpperCase = true;
else if (char.IsLower(c))
hasLowerCase = true;
else if (char.IsDigit(c))
numDigits++;
}
if (!hasUpperCase || !hasLowerCase || numDigits < 2)
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
用法:
[CustomPassword(ErrorMessage = "Password must be at least 8 characters in length, contain both uppercase and lowercase characters, and at least 2 numbers.")]
public string Password { get; set; }