ASP NET如何给模型验证注解添加条件?
ASP NET how to add a condition to a model validation annotation?
我的表单中有密码确认功能。但是,如果用户已经登录,我会隐藏该表单中的密码和密码确认字段。
提交此表单时,如果浏览器存储了来自网站的任何 "password" 字段,那么我的模型正在验证确认密码,这会导致错误。
如何向此验证添加条件,以便在用户已登录时不会触发它。
[Display(Name="Confirm Password")]
[DataType(DataType.Password)]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "Passwords do not match")]
[RequiredIfEqual("LoggedIn", false, ErrorMessage = "This field is required")]
public string PasswordConfirm { get; set; }
您不能为默认 Compare
属性添加条件。
您可以根据您的需求编写自定义属性,在属性中您可以获得HttpContext.Current.Session["Login"] != null
并检查您的逻辑。
您可以参考这个来实现自定义比较属性
https://www.codeproject.com/Tips/780992/Asp-Net-MVC-Custom-Compare-Data-annotation-with-Cl
我的表单中有密码确认功能。但是,如果用户已经登录,我会隐藏该表单中的密码和密码确认字段。
提交此表单时,如果浏览器存储了来自网站的任何 "password" 字段,那么我的模型正在验证确认密码,这会导致错误。
如何向此验证添加条件,以便在用户已登录时不会触发它。
[Display(Name="Confirm Password")]
[DataType(DataType.Password)]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "Passwords do not match")]
[RequiredIfEqual("LoggedIn", false, ErrorMessage = "This field is required")]
public string PasswordConfirm { get; set; }
您不能为默认 Compare
属性添加条件。
您可以根据您的需求编写自定义属性,在属性中您可以获得HttpContext.Current.Session["Login"] != null
并检查您的逻辑。
您可以参考这个来实现自定义比较属性
https://www.codeproject.com/Tips/780992/Asp-Net-MVC-Custom-Compare-Data-annotation-with-Cl