如何从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)]
答案 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")
...
}