Is there a way to stop the DataAnnotation check after the first failure?

In my ViewModels, I use several DataAnnotations to validate form data, usually 2-3 annotations per field.

For example, a field for an email address might look like this:

[Required(ErrorMessage = "Please enter an email address.")]
[Email(ErrorMessage = "That is not a valid email address.")] // Custom
public string Email { get; set; }

Now, if someone had to submit the form, both errors will appear in the validation summary. Is there any easy way to specify an order to trigger validation annotations so that if the mandatory validation fails, the email validation fails?

If this is not possible, how is it usually handled? Should I create custom validators for any field containing more than one annotation? Would this be the right way to use annotations where one handles several types of validation?

(I also know that maybe I could combine the required annotation with a custom email, but this is just an example).

+3
source share
3 answers

In this particular case, I probably follow the same approach as ASP.NET WebForms validators - just return return true EmailAttributeif the value is nullempty.

Think about it:

  • If an email address is required, there will also be a validator [Required], and a null / empty email address will still generate a validation error;

  • If the email address is optional, null / empty should be considered valid.

, !

+1

: .

, "" " .

, AFAIK, , , , .

+1

, . . - xVal , , orderby, , :

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

, T ValidationAttribute.

+1

Source: https://habr.com/ru/post/1733644/


All Articles