如何从视图模型访问密码验证器属性以装饰输入密码验证?
例如,这是在 IdentityConfig.cs/Create 中
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 7,
RequireNonLetterOrDigit = false,
RequireDigit = true,
RequireLowercase = false,
RequireUppercase = false,
};
然后在帐户视图模型中.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)]
可能有更好的方法,但考虑到您希望在密码验证程序和视图模型之间共享配置并使它们保持同步,您可以使用应用程序设置将配置外部化,这将允许您保持两个类分离。
因此,您可以将应用程序设置添加到您的 web.config(如果使用 .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")
...
}