There was an attempt to include server-side DataAnnotation data validation in my project, and I found that DataAnnotations has its own error type - ValidationException. My problem with this, however, is that it only returns one validation error at a time, so if 3 properties fail the validation, only the first one is selected. I’m looking for a way to throw all errors as an exception, so instead of informing the user / developer that the check did not pass, he will indicate which properties / fields the check failed at one time.
I found the Validator.TryValidateObject (...) method, but it just populates the ValidationResults and leaves the developer with the option to throw and drop or not. What I am currently implementing iterates through ValidationResults to create a list of ValidationExceptions from this, completes the list in an AggregateException, and then throws another ValidationException using the AggregateException in its internal values.
ValidationContext validationContext = new ValidationContext(entity, null, null); List<ValidationResult> validationResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(entity, validationContext, validationResults, true); if (!isValid) { List<ValidationException> validationErrors = new List<ValidationException>(); foreach (ValidationResult validationResult in validationResults) { validationErrors.Add(new ValidationException(validationResult.ErrorMessage); } throw new ValidationException("Entity validation failed.", new AggregateException(validationErrors)); }
So basically my questions are:
- Is there a reason why there is no built-in way to throw multiple errors at the same time? That is, is there any good practice missing with DataAnnotation Validations?
- Is there a better way to achieve what I was trying to implement?
- Also ... how can I include a member name when moving a ValidationResult to a Validation exception?
c # validation error-handling data-annotations
iamnobody
source share