如何指定 DataAnnotation ValidationAttribute 的顺序? [英] How can I specify the order of DataAnnotation ValidationAttribute's?

查看:28
本文介绍了如何指定 DataAnnotation ValidationAttribute 的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题这里是相似的,但我没有任何域对象继承.我的字段和验证标记按以下顺序排列,但 MustBe18 错误和必需错误是唯一打印的错误.我在此模型中还有其他几个字段进行了更多验证,但代码中 ValidationAttribute 的顺序似乎并不重要.jfar 在链接帖子中的回答似乎暗示可以构建一个助手,但是如何构建?订单怎么控制?

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(ErrorMessage = "You must be 18 years old")]
[MustNotBeOver100(ErrorMessage = "This caller is too old")]
public string dob { get; set; }

MustBe18 : ValidationAttribute(重载的 IsValid 方法)

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;
}

推荐答案

指定顺序的唯一方法是创建自己的ModelValidatorProvider 然后可以对属性进行排序.这可能会很棘手,因为您还需要为采用 Order 参数的每个属性创建重载(不知道他们是否已经这样做了).

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 ).

如果您只关心验证摘要出现的顺序,那么您需要做的就是遍历 ModelState 条目并从那里吐出错误.

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.

这篇关于如何指定 DataAnnotation ValidationAttribute 的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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