Search code examples
javaspring-boothibernate-validator

Validate all fields at once using hibernate validator


I'm using Spring Boot 2.2.0 to build a restful service with the java bean validation framework. Hibernate-Validator is used behind the scenes. The validation works well but throws an exception after one field fails to match the constraint. I would like to validate all fields first and then give the consumer a response with all errors. Is that possible?


Solution

  • Assuming you use @Valid annotation on your request, there is a MethodArgumentNotValidException that you could use in an @ExceptionHandler method in order to achieve that.

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public List<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        //get All errors with
        ex.getBindingResult().getAllErrors();
        //and map them
    }