使用 DataAnnotations 比较两个模型属性 [英] Using DataAnnotations to compare two model properties

查看:38
本文介绍了使用 DataAnnotations 比较两个模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何编写比较两个字段的自定义 ValidationAttribute?这是常见的输入密码"、确认密码"场景.我需要确保这两个字段相等并保持一致,我想通过 DataAnnotations 实现验证.

How would I go about writing a custom ValidationAttribute that compares two fields? This is the common "enter password", "confirm password" scenario. I need to be sure the two fields are equal and to keep things consistent, I want to implement the validation via DataAnnotations.

所以在伪代码中,我正在寻找一种方法来实现如下内容:

So in pseudo-code, I'm looking for a way to implement something like the following:

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?

So the question is, how do I code the [Compare] ValidationAttribute?

推荐答案

在 ASP.NET MVC 3 框架中有一个 CompareAttribute 可以做到这一点.如果您使用的是 ASP.NET MVC 2 并针对 .Net 4.0,那么您可以查看 ASP.NET MVC 3 源代码中的实现.

There is a CompareAttribute in the ASP.NET MVC 3 Framework that does this. If you are using ASP.NET MVC 2 and targeting .Net 4.0 then you could look at the implementation in the ASP.NET MVC 3 source code.

这篇关于使用 DataAnnotations 比较两个模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆