c# - 使用 DataAnnotations 比较两个模型属性

标签 c# asp.net-mvc validation data-annotations

我将如何着手编写比较两个字段的自定义 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/

相关文章:

symfony - 如何为 NotEqualTo 约束定义一组值?

c# - MVC 条件验证?

c# - 保护代码中敏感数据的最佳方法是什么?

c# - 在 unix (nginx) 上托管时 .NET Core 中的 TimeZoneInfo

c# - 我如何解释此 C# 堆栈跟踪?零行错误

c# - 无法加载类型 'System.Web.Mvc.ViewPage'

c# - Entities Framework 6 alpha 2 - 异步模式

c# - 访问 session 对象

asp.net-mvc - ASP.NET MVC TextBoxFor 占位符

c# - c# winforms 应用程序中的电子邮件验证