Reputation: 522
I have several input fields in registration form. For example, there are 5 fields. 'Email' and "Phone Number" fields are wrong, I do not want to display both validation errors. I only want to check "Email" field and display Email error, if it will be correctly written on second try, only then 'Password' error message can appear.
Can I accomplish it with server-side validation only?
Screenshot: Both validation errors are displayed at the same time.
Upvotes: 0
Views: 1154
Reputation: 27538
You can dynamically modify the ModelState
and check the errors :
if (ModelState.IsValid)
{
....
}
else
{
var flag = false;
foreach (var modelState in ViewData.ModelState.Values)
{
if (flag)
{
modelState.Errors.Clear();
}
if (modelState.Errors.Count >0)
{
flag = true;
}
if (modelState.Errors.Count>1)
{
var firstError = modelState.Errors.First();
modelState.Errors.Clear();
modelState.Errors.Add(firstError);
}
}
}
return View("index", movie);
Upvotes: 1
Reputation: 5719
Set maximum model validation errors to 1 in stratup, the validation process stops when max number is reached (200 by default):
services.AddMvc(options =>
{
options.MaxModelValidationErrors = 1;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
but in this case it will stop on the first error even if there is more than one validation error on the same property (e.g. password length is not valid, password must contain upper case letter, etc...).
If you need to show all errors at once for each property you will need another solution.
ref: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2
Upvotes: 0