How to determine which ValidationAttribute returned a ModelError
Asked Answered
I

1

6

I'm having an issue where I am trying to determine which ValidationAttribute returned a particular ModelError. I have an endpoint in my web api that takes a model such as;

public class MyClass
{
    [Required]
    [Range(0, 3)]
    public int? Number { get; set; }

    [Required]
    [Range(0, 3)]
    public int? NumberTwo { get; set; }
}

and a filter to check that the ModelState is valid;

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            IEnumerable<ModelError> errors = actionContext.ModelState.Values.SelectMany(s => s.Errors);
            // ...
        }
    }
}

I see that the ModelError has two properties; ErrorMessage which is of type string, and Exception which is of type Exception. I would like a strongly typed way to determine which ValidationAttribute [Required] or [Range(0, 3)] returned the error response without doing string manipulation. Is there a way to return a custom property using these attributes that I am unfamiliar with?

If the client were to post a model such as

{
    "NumberTwo":10
}

The end goal would be to produce a response from the API such as the following;

{
    "supportCode" : "1234567890",
    "errors" : [{
        "code" : "Missing",
        "message" : "The Number field is required."
    }, {
        "code" : "Invalid",
        "message" : "The field NumberTwo must be between 0 and 3."
    }] 
}
Immaculate answered 11/9, 2015 at 15:4 Comment(0)
F
0

It is possible if you write your own validation routine instead of using the one built into MVC. You'll need to use reflection over each property, and then over each validation attribute on each property.

Foolhardy answered 13/9, 2015 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.