3

I know this question is asked several times for other frameworks and languages but I wanted to know how can I really stop my model validation once it gets the first error in ASP.NET Core 2.1?

    [Required(ErrorMessage = Email.requiredErrorMessage)]
    [DataType(DataType.EmailAddress, ErrorMessage = Email.formatErrorMessage)]
    [StringLength(Email.maximumLength, MinimumLength = Email.minimumLength, ErrorMessage = Email.rangeErrorMessage)]
    [EmailExists(ErrorMessage = Email.doesNotExistsMessage)]
    public string email { get; set; }

    [Required(ErrorMessage = ConfirmationCode.requiredErrorMessage)]
    [RegularExpression(ConfirmationCode.regularExpression, ErrorMessage = ConfirmationCode.formatErrorMessage)]
    public string confirmationCode { get; set; }

Above code is API model validation and upon making a Patch request, I receive following response:

"email":[
"This email does not exist in database"
],
"confirmationCode":[
"Confirmation code format is invalid"
]
}

I do not want model validation to continue when it has ensured that email doesn't exist in database, just return that error and do not continue the validation anymore.

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Suleman
  • 644
  • 3
  • 12
  • 23

1 Answers1

6

You can configure the maximum number of errors MVC will process when you register the MVC services:

services.AddMvc(options => options.MaxModelValidationErrors = 1);

See https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#model-state

MVC will continue validating fields until reaches the maximum number of errors (200 by default). You can configure this number by inserting the following code into the ConfigureServices method in the Startup.cs file:

That being said, you won't necessarily have control over which order those errors are processed in. To handle that, you might need to add some custom validation logic which is also discussed in the above link.

Eric Damtoft
  • 1,353
  • 7
  • 13