我希望正則表達式在模型中有辦法做到這一點?在mvc中限制常見密碼,如qwerty,123456789
我讀了這個答案安東尼Pegram在以下問題這樣的邏輯,而在MVC驗證 ASP.net PasswordStrengthRegularExpression to prevent common passwords like "11111" or "123456"
我希望正則表達式在模型中有辦法做到這一點?在mvc中限制常見密碼,如qwerty,123456789
我讀了這個答案安東尼Pegram在以下問題這樣的邏輯,而在MVC驗證 ASP.net PasswordStrengthRegularExpression to prevent common passwords like "11111" or "123456"
那麼最簡單的解決辦法是讓你的模型幫助從IValidatableObject繼承和實現validate方法在模型中,這樣的事情:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(Password) == false)
{
var passwordValid = true;
for (int i = 2; i < Password.Length; i++)
{
if (Password[i] == Password[i - 1] - 1 && Password[i - 1] == Password[i - 2] - 1)
{
passwordValid = false;
}
else if (Password[i] == Password[i - 1] + 1 && Password[i - 1] == Password[i - 2] + 1)
{
passwordValid = false;
}
else if (Password[i] == Password[i - 1] && Password[i - 1] == Password[i - 2])
{
passwordValid = false;
}
}
if (!passwordValid)
{
yield return new ValidationResult("Your Validation Message Here!", new []{ "Password" });
}
}
}
另一種選擇是用類似的邏輯添加擴展方法爲你的模型,然後檢查控制器的結果:
if (!model.IsValidPassword())
{
ModelState.AddModelError("", "Your Validation Message Here!");
return View(model);
}
[RegularExpression(@"(?=^.{8,30}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[email protected]#$%^&*()_+}{"":;'?/>.<,]).*$",ErrorMessage="Password must have at least 1 small-case letter At least 1 Capital letter At least 1 digit At least 1 special character Length should be between 8-30 characters")]
public string NewPassword { get; set; }
這將是強密碼的代碼我怎樣才能聯繫起來。請標記爲答案,如果從這個職位
謝謝你的回答,但是這不是我所期待FO r –
你能描述一下你的情況嗎?這樣我可以改進我的答案,以便它可以幫助解決你的問題。 –
閱讀由Anthony Pegram提供的答案,我給的鏈接其實我想在我的模型中使用該邏輯 –
添加'RegularExpressionAttribute'你的財產 –