Search code examples
hibernatehibernate-validator

Access List index in customer hibernate validator message


I am validating a list of vehicles, I want to provide a custom message to the user that describes the error a little better.

I can currently use

NotNull.vehicle.name = 'Vehicle name has not been filled in'

however if there were 10 vehicles in the list there is no indication of which vehicle was in error, I want to do something like this

NotNull.vehicle[0].name = 'Vehicle item {index + 1}: name has not been filled in'

Is something like this possible?


Solution

  • It's not possible out of the box, using the built-in constraints.

    You could implement a custom constraint and validator for List<Car> and create the constraint violation and its message yourself. Using the node builder API you still could have the violation point the right element:

    public class CarListValidator
        implements ConstraintValidator<ValidCarList, List<Car>> {
    
        @Override
        public void initialize(ValidCarList constraintAnnotation) {
        }
    
        @Override
        public boolean isValid(List<Car> cars, ConstraintValidatorContext constraintValidatorContext) {
    
            boolean isValid = ...;
    
            if ( !isValid ) {
                int invalidIndex = ...;
    
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext
                    .buildConstraintViolationWithTemplate( 
                        "name missing for car #" + invalidIndex 
                    )
                        .addPropertyNode( "name" )
                        .inIterable()
                        .atIndex( invalidIndex )
                    .addConstraintViolation();             
            }
    
            return isValid;
        }
    }