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

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

问题描述

问题<一href="http://stackoverflow.com/questions/3912728/how-to-specify-order-of-data-annotation-errors-in-html-validationsummary">here是相似的,但我没有任何域对象继承。我的字段和验证标记是按以下顺序,但MustBe18误差和必需误差是唯一的打印。我在这个模型更验证等几个领域,但ValidationAttribute的在code的顺序似乎并不重要。在链接后jfar的回答似乎表明可以建立一个帮手,但如何?如何能在顺序控制?

  [必需的(的ErrorMessage =这是必须填写)
[DisplayName的(出生日期)
[MustBeValidDate(的ErrorMessage =必须是一个有效日期)
[MustBe18(的ErrorMessage =您必须年满18岁)
[MustNotBeOver100(的ErrorMessage =这主叫太旧)
公共字符串DOB {获得;组; }
 

MustBe18:ValidationAttribute(重载IsValid的方法)

 尝试
{
    日期时间DOB =新的日期时间(DateTime.Now.AddYears(-18).Year,DateTime.Now.Month,DateTime.Now.Day);
    返回DateTime.Compare(DateTime.Parse(value.ToString()),DOB)所述; = 0;
}
抓住
{
    返回false;
}
 

解决方案

要指定顺序的唯一方法是创建自己的<一href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelvalidatorprovider%28v=vs.98%29.aspx"相对=nofollow> ModelValidatorProvider 然后可以订购属性。这可能会非常棘手,因为你也想需要创建的重载为每个属性接受一个订单的参数(不知道是不是他们已经这样做了)。

如果你介意的是在验证摘要显示所有你需要做的是遍历ModelState中的条目,并从那里吐出错误的顺序。

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

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

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