使用DataAnnotations来比较两个模特属性 [英] Using DataAnnotations to compare two model properties
问题描述
我将如何去写一个比较两个字段的自定义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.
因此,在伪code,我正在寻找一种方式来实现类似以下内容:
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)
{
// ??
}
}
所以,问题是,我怎么code中的[比较] ValidationAttribute?
So the question is, how do I code the [Compare] ValidationAttribute?
推荐答案
有一个CompareAttribute在ASP.NET MVC 3框架,做到这一点。如果你正在使用ASP.NET MVC 2和定位.NET 4.0,那么你可以看一下在ASP.NET MVC 3源$ C $ c中的执行情况。
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屋!