Search code examples
javahibernatebean-validationhibernate-validator

How do you get the Property Paths from a Class level Annotation violation


I'm using Hibernate Validator. I have a Class level annotation. It compares three properties for equality. When the validation is performed I need to get the PropertyPaths from the javax.validation.ConstraintViolation object returned. Since it's not a single field the getPropertyPath() method returns null. Is there another way to find the PropertyPaths?

This is my annotation implementation -

@MatchField.List({
@MatchField(firstField = "firstAnswer", secondField = "secondAnswer", thirdField = "thirdAnswer"),
})

Solution

  • You need to set the messages to map to the properties that you want rejected when you do the validation. Hibernate Validator has no way to auto-magically figure out that custom annotation properties are property paths.

    public class MatchFieldValidator implements ConstraintValidator<MatchField, Object> {
    
      private MatchField matchField;
    
      @Override
      public void initialize(MatchField matchField) {
        this.matchField = matchField;
      }
    
      @Override
      public boolean isValid(Object obj, ConstraintValidatorContext cvc) {
    
        //do whatever you do
        if (validationFails) {
          cvc.buildConstraintViolationWithTemplate("YOUR FIRST ANSWER INPUT IS WRONG!!!").
                            addNode(matchField.firstAnswer()).addConstraintViolation();
          cvc.buildConstraintViolationWithTemplate("YOUR SECOND ANSWER INPUT IS WRONG!!!").
                            addNode(matchField.secondAnswer()).addConstraintViolation();
          //you get the idea
          cvc.disableDefaultConstraintViolation();
          return false;
        }
      }
    }