1

The default validation messages all end with a full stop and I want to remove this for every property validation message without having to add a custom ErrorMessage format for each validation attribute.

.NET 6 validation messages

I've tried looking at setting methods in ModelBindingMessageProvider when adding Mvc as part of my Startup.cs class. No success with this...

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
George Feakes
  • 152
  • 2
  • 13
  • Does this helpful? https://stackoverflow.com/questions/64339575/global-error-handler-including-model-binder-errors and here is an other reference https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0 – MichaelMao Jan 10 '23 at 10:30

1 Answers1

3

The error message is come from ModelError in the ModelState but it doesn't have set method so we can't override the error message template(as far as I know). I have 2 ways to do it, first one is create a new ModelError instance so you can assing the error message what you want, second one is almost same as first one but you can keep the filed name in error message.

Method 1

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = (actionContext) =>
    {
        foreach (var x in actionContext.ModelState)
        {
            for (var i = 0; i < x.Value.Errors.Count; i++)
            {
                x.Value.Errors[i] = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelError("Your message here");
            }
        }

        var problemDetails = new ValidationProblemDetails(actionContext.ModelState);

        problemDetails.Type = options.ClientErrorMapping[400].Link;
        problemDetails.Title = "One or more validation errors occurred.";
        problemDetails.Status = StatusCodes.Status400BadRequest;

        return new BadRequestObjectResult(problemDetails);
    };
});

Method 2

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = (actionContext) =>
    {
        var errorDictionary = new Dictionary<string, string[]>(StringComparer.Ordinal);
        var errorMessageTemplate = "Your message here, The field {0} is required";
        foreach (var keyModelStatePair in actionContext.ModelState)
        {
            var key = keyModelStatePair.Key;
            var errors = keyModelStatePair.Value.Errors;
            if (errors != null && errors.Count > 0)
            {
                if (errors.Count == 1)
                {
                    var errorMessage = errorMessageTemplate;
                    errorDictionary.Add(key, new[] { string.Format(errorMessage, key) });
                }
                else
                {
                    var errorMessages = new string[errors.Count];
                    for (var i = 0; i < errors.Count; i++)
                    {
                        errorMessages[i] = errorMessageTemplate;
                    }

                    errorDictionary.Add(key, errorMessages);
                }
            }
        }

        var errorModel = new
        {
            Type = options.ClientErrorMapping[400].Link,
            Title = "One or more validation errors occurred.",
            Status = StatusCodes.Status400BadRequest,
            Errors = errorDictionary
        };
        return new BadRequestObjectResult(errorModel);
    };
});
MichaelMao
  • 2,596
  • 2
  • 23
  • 54