0

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 ?

Tim Ta
  • 41
  • 2
  • 5
  • Bean validation ConstraintViolationException contains all the validation errors. – Paul Samsotha Mar 22 '22 at 15:25
  • okay thank you. I missed that fact. How can I ensure, that this exception will be thrown and not the "MethodArgumentNotValidException" ? And how can I write own validators with this exception? I saw just the linked article above and there I overwrite a boolean isValid method, which returns true or false and no list of invalid arguments. – Tim Ta Mar 22 '22 at 16:06

0 Answers0