访问数据注释错误消息中的PasswordValidator

时间:2017-08-14 14:30:51

标签: c# asp.net-mvc asp.net-identity

如何从viewmodel访问PasswordValidator属性以装饰输入密码验证?

例如,这是在IdentityConfig.cs / Create

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 7,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = false,
            RequireUppercase = false,
        };

然后在AccountViewModels.cs

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

在密码输入长度正确之前,属性[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 7)]会阻止提交表单。如果我删除它,表单可能会被发布但由于PassordValidator会产生错误,所以我认为最好有这个属性,所以在正确之前不能发布任何内容。

如何访问RegisterViewModel中的PasswordValidator属性?

例如

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = passwordValidator.RequiredLength)]

1 个答案:

答案 0 :(得分:1)

可能有更好的方法,但考虑到您希望在passwordvalidator和viewmodel之间共享配置并使它们保持同步,您可以使用应用程序设置来外部化配置,这样可以使两个类保持分离。 / p>

所以你可以在web.config中添加appsetting(如果使用.NET Core,则为appsettings.json)

示例(伪代码,未检查它编译但显示了想法)

的web.config:

<appSettings>
  <add key="passwordminlength" value="6" />
...
</appSettings>

属性:

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = (int) ConfigurationManager.AppSettings["passwordminlength")]

验证

manager.PasswordValidator = new PasswordValidator
{
   RequiredLength = (int) ConfigurationManager.AppSettings["passwordminlength")
   ...
}