I want to have a rest endpoint which returns all invalid input fields with a reason, which explains the invalidity.
For that, I need to implement a validation method in each DTO class, which will be received by the rest endpoint. Now I'm asking myself if there is already a good approach to do that. I'm thinking about the spring validation. But I think there will be only thrown a "MethodArgumentNotValidException", which contains one invalid argument !?
Further, I could build a custom builder, but I think I can just define when the class is valid and when not and not change the error result: How can I validate two or more fields in combination?
Is there an existing way to validate multiple arguments at the same time and to return a list of all invalid arguments with a reason? Otherwise, I would build such a validation for my purpose.
T
€dit: Okay, I found this https://www.baeldung.com/spring-mvc-custom-validator and the information that when I do this for validation I get a list of all messages and parameter names:
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
final var validator = factory.getValidator();
final Set<ConstraintViolation<DtoResponse>> violations = validator.validate(tmp);
for (final ConstraintViolation<DtoResponse> violation : violations) {
log.error(violation.getPropertyPath().toString() + " - " + violation.getMessage());
}
Now I have a last problem. When I write a verification for a whole class (ElementType.TYPE) (https://www.baeldung.com/spring-mvc-custom-validator#custom-class-level-validation) then the getPropertyPath() of the ConstraintViolation is empty. Is there a way to insert there a name ?