如何指定 DataAnnotation ValidationAttribute 的顺序?

发布于 2024-10-09 00:01:46 字数 784 浏览 0 评论 0 原文

这里的问题是类似的,但我没有任何域对象继承。我的字段和验证标签按以下顺序排列,但 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;
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满身野味 2024-10-16 00:01:46

指定顺序的唯一方法是创建您自己的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文