I have an ASP.NET Core 6 Web API project with all controllers decorated with the [ApiController] annotation. I use validation annotations like [Required], [MaxLength] etc. to validate properties of DTOs received in incoming requests.
Some of my DTOs also implement the IValidatableObject interface, to handle more complex validation scenarios not covered by the attributes.
When DTO in the request is invalid because IValidatableObject.Validate() returned some ValidationResults, the corresponding validation error messages appear in the response.
But when the DTO ALSO has validation errors because of the attributes, only attribute-related error messages appear in the response.
How can I get all errors to appear?
Here's another, more complex scenario, when not all errors appear in the response. Let's say I have two DTOs - Parent and Child. Parent has property Children of type ICollection<Child>. Child has some validation attributes on its properties. Parent has a validation attribute on the Children property that checks that the property value, which is a collection, does not contain nulls.
If in the request I send a Parent with Children collection containing two items - an invalid Child and a null, the response has only one error message, the one about the invalid child. If I make the child valid, then the message about null in the Children collection starts coming up.
If you want to show error message together, You can custom validation attribute with
ValidationAttributeinstead of implementIValidatableObject, Here is a simple demo:Model
Now if the request model is invalid, It will response all the error message.