我将如何着手编写比较两个字段的自定义 ValidationAttribute?这就是常见的“输入密码”、“确认密码”的场景。我需要确保这两个字段相等并保持一致,我想通过 DataAnnotations 实现验证。
所以在伪代码中,我正在寻找一种方法来实现如下内容:
public class SignUpModel
{
[Required]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Display(Name = "Re-type Password")]
[Compare(CompareField = Password, ErrorMessage = "Passwords do not match")]
public string PasswordConfirm { get; set; }
}
public class CompareAttribute : ValidationAttribute
{
public CompareAttribute(object propertyToCompare)
{
// ??
}
public override bool IsValid(object value)
{
// ??
}
}
所以问题是,我该如何编写 [Compare] ValidationAttribute 代码?
最佳答案
确保您的项目引用了 system.web.mvc v3.xxxxx。
那么你的代码应该是这样的:
using System.Web.Mvc;
. . . .
[Required(ErrorMessage = "This field is required.")]
public string NewPassword { get; set; }
[Required(ErrorMessage = "This field is required.")]
[Compare(nameof(NewPassword), ErrorMessage = "Passwords don't match.")]
public string RepeatPassword { get; set; }
关于c# - 使用 DataAnnotations 比较两个模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938078/