Is there any way to stop DataAnnotation validation after the first failure?

泄露秘密 提交于 2019-12-05 18:30:05

In this specific case I would probably take the same approach that the ASP.NET WebForms validators take - simply have the EmailAttribute validator return true if the value is null or empty.

Think about it:

  • If the e-mail address is required, then there will also be a [Required] validator and a null/empty e-mail address will generate a validation error anyway;

  • If the e-mail address is optional, a null/empty value should be considered valid.

No need to solve the complex problem of intercepting validators when you can just design the individual validators to play nice together!

Ordering validation: No.

In this case you could simply remove the Required attribute because "" or " " will fail the email address validation.

And yes, AFAIK creating a custom validation attribute that combines both of them is probably your best bet.

The problem here is that the ordering on the attributes is completely arbitrary and decided at compile time. You actually can enforce simple ordering depending on the kind of validation runner you're using. If you are using something like xVal and a validation runner like the one mentioned here, you can add an orderby clause like this to force a specific kind of attribute to sort to the top:

orderby attribute.GetType() == typeof(T) ? 0 : 1

Just make a strongly-typed validation runner method, where T is derived from the ValidationAttribute class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!