I have the following model defined
public class User
{
[EmailAddress(ErrorMessage = "The Email Address is not valid.")]
[Required(ErrorMessage = "Please enter an email address.")]
[StringLength(5, ErrorMessage = "The Email Address must be less than 5 characters.")]
[Display(Name = "Email Address:")]
public string EmailAddress { get; set; }
}
Now, when the incoming http post request has following payload, which doesn't satisfy two data annotations such as StringLength and EmailAddress, how do I find out which data annotations failed for the property EmailAddress?
{
"EmailAddress": "Raj.xyz.com"
}
I could not find anything in ModelState which would let me know what are the data annotations failed.
If you run validation by yourself using
System.ComponentModel.DataAnnotations.Validator.Then your code would look like:
The code prints the output to the console:
As you can see, you pass a
List<ValidationResult>to theValidator. It fills the list with validation errors.ValidationResultinstance has:.MemberNamesproperty that indicates the property names which failed validation,.ErrorMessageproperty that provides a human-readable error that can be shown to an end-user.If you do it in Web API, you need:
Create your validation filter and get access to the
ModelState:Add DI registrations:
Put filter on your controller: