Search code examples
c#asp.net-coremodelstatemodelstatedictionary

Get individual error messages from modelstate


How to get individual error messages from modelstate? Currently, if I not populate required fields I will get the following message:

JSON deserialization for type 'MyType' was missing required properties, including the following: property1, property2, property3

I'd like to get message per field, is it possible?

I'm getting the error list using the following code:

var modelStateErrors = context.ModelState.Values.SelectMany(m => m.Errors);

Solution

  • This might be what you're looking for:

    var errorDictionary = ModelState
        .Where(e => e.Value?.Errors.Count > 0)
        .ToDictionary(
            kvp => kvp.Key,
            kvp => kvp.Value?.Errors.Select(e => e.ErrorMessage).ToList());
    

    If you return the dictionary as a JSON response you could get something like this (depending on the model annotations or lack thereof):

    {
        "Username": ["Username is required."],
        "Password": ["Password must be at least 6 characters.", "Password must contain a number."]
    }
    

    The error messages in the JSON response come from the data annotations applied to your model's properties. By default ASP.NET Core provides some default validations if the property is not manually annotated.

    For more info check out: asp.net core docs.