Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use single error message template for all invalid properties

Imagine a razor page with a Form that have many inputs that user fills them.

with post method when it wants to validate the posted model like this :

public IActionResult OnPost()
{
     if (!ModelState.IsValid)
     {
        return Page(model);
     }
}

If for example 3 property of that model (with names : a,b,c) are not valid, it turns back to the razor view and shows the error (because of asp-validation-for for each property) like this :

The a field is required.
The b field is not a valid e-mail address.
The c field is required.

I want to show a specific error for all of them like this :

This Input is not valid.
This Input is not valid.
This Input is not valid.

I know I can use (ErrorMessage ="") for each of them separately, but its not logical in big size! is there any way to show a specific massage for all of invalid ModelStates?

Edit:

For example before showing errors in View, change their error message like this :

@foreach (var error in modelStateErrors)
{
    error.text = "Fill it";
}

enter image description here

like image 952
nima ansari Avatar asked Dec 30 '22 20:12

nima ansari


1 Answers

I created a solution with an extension method for ModelState.
It basically removes any errors from the state and adds them back with the desired message.

Create a ModelStateExtensions.cs in your namespace:

public static class ModelStateExtensions
{
    public static void SetAllErrorMessages(this ModelStateDictionary modelState, string errorMessage)
    {
        foreach (var state in modelState)
        {
            if (state.Value.Errors.Count > 0)
            {
                modelState.Remove(state.Key);
                modelState.AddModelError(state.Key, errorMessage);
            }
        }
    }
}

Then if your ModelState is invalid you can transform the message before returning the page:

public IActionResult OnPost()
{
     if (!ModelState.IsValid)
     {
        ModelState.SetAllErrorMessages("Your message here");
        return Page(model);
     }
}
like image 186
Jay Fridge Avatar answered Jan 14 '23 12:01

Jay Fridge