Search code examples
javahibernate-validator

Add more properties to ConstraintViolation


I am new to using Hibernate validator and apparent I can only get error message and property path from ConstraintViolation.

What I want to do is to provide more information. For e.g. If I am testing a integer's max value where my max limit keeps changing I want to add max value apart from error message and property path :

  1. Error message : some error message
  2. Max value : 30
  3. Property path : some.property.path

    public boolean isValid(final Integer integer, final ConstraintValidatorContext constraintValidatorContext) {
    
        boolean isValid = true;
        if(integer >= SomeClass.maxValue) {
    
            context.disableDefaultConstraintViolation();
    
            context.buildConstraintViolationWithTemplate("some error message")
            .addPropertyNode("some.property.path")
            .addConstraintViolation();
    
            isValid = false;
            break;
    
        }
        return isValid;
    }
    

Any idea on how to do it ?


Solution

  • The idea is to use the dynamic payload feature as explained here: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-dynamic-payload in details. For instance:

    HibernateConstraintValidatorContext hibernateContext = context.unwrap(
        HibernateConstraintValidatorContext.class
    );
    hibernateContext.withDynamicPayload( yourAdditionalInformation );
    

    In the examples of the documentation, we only include a simple value but you can inject a bean containing all the properties you need.

    Note that this is an Hibernate Validator-specific feature (thus the need to unwrap the context to its Hibernate Validator-specific counterpart).