在mvc中限制qwerty,123456789等常用密码

时间:2016-07-04 08:56:31

标签: asp.net-mvc

我希望正则表达式在模型中有没有办法做到这一点?

我在下面的问题中通过Anthony Pegram读到了这个答案,如何在mvc中验证时将这个逻辑联系起来 ASP.net PasswordStrengthRegularExpression to prevent common passwords like "11111" or "123456"

2 个答案:

答案 0 :(得分:1)

最简单的解决方案是让模型继承自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);
}

答案 1 :(得分:0)

[RegularExpression(@"(?=^.{8,30}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*()_+}{&quot;&quot;:;'?/&gt;.&lt;,]).*$",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; }

这将是强密码的代码。如果从这篇文章中获得帮助,请标记为答案