如何指定 DataAnnotation ValidationAttribute 的顺序?
这里的问题是类似的,但我没有任何域对象继承。我的字段和验证标签按以下顺序排列,但 MustBe18 错误和必需错误是唯一打印的错误。我在此模型中还有其他几个字段,需要进行更多验证,但代码中 ValidationAttribute 的顺序似乎并不重要。 jfar 在链接帖子中的回答似乎表明可以构建一个助手,但是如何构建呢?如何控制订单?
[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 方法)
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
指定顺序的唯一方法是创建您自己的 ModelValidatorProvider 然后可以对属性进行排序。这可能会很棘手,因为您还需要为每个采用 Order 参数的属性创建重载(不知道它们是否已经这样做了)。
如果您只关心验证摘要出现的顺序,那么您需要做的就是循环遍历 ModelState 条目并从那里吐出错误。
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.