开发者

How can I specify the order of DataAnnotation ValidationAttribute's?

The question here is similar, but I don't have any domain object inheritance. My field and validation tags are in the following order, but the MustBe18 error and the Required error are the only ones that print. I have several other fields in this model with much more validation, but the order of ValidationAttribute's in the code doesn't seem to matter. jfar's answer in the linked post seems to suggest a helper could be built, but how? How can the order be controlled?

[Required(ErrorMessage = "This field is required")]
[DisplayName("Date of Birth")]
[MustBeValidDate(ErrorMessage = "Must be a valid date")]
[MustBe18(ErrorMessa开发者_JAVA技巧ge = "You must be 18 years old")]
[MustNotBeOver100(ErrorMessage = "This caller is too old")]
public string dob { get; set; }

MustBe18 : ValidationAttribute (the overloaded IsValid method)

try
{
    DateTime dob = new DateTime(DateTime.Now.AddYears(-18).Year, DateTime.Now.Month, DateTime.Now.Day);
    return DateTime.Compare(DateTime.Parse(value.ToString()), dob) <= 0;
}
catch
{
    return false;
}


The only way to specify the order is to create your own ModelValidatorProvider which can then order the attributes. This will probably be tricky because you'd also need to create overloads for each attribute that takes an Order parameter ( don't know if they already do ).

If all you mind is the order in which validation summaries appear all you'd need to do is loop through the ModelState entries and spit out the errors from there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜