I\'ve written a validation annotation implemented by a custom ConstraintValidator
. I also want to generate very specific ConstraintViolation
objects th
That's not possible with the standardized Bean Valiation API, but there is a way in Hibernate Validator, the BV reference implementation.
You need to unwrap the ConstraintValidatorContext
into a HibernateConstraintValidatorContext
which gives you access to the addExpressionVariable()
method:
public class MyFutureValidator implements ConstraintValidator {
public void initialize(Future constraintAnnotation) {}
public boolean isValid(Date value, ConstraintValidatorContext context) {
Date now = GregorianCalendar.getInstance().getTime();
if ( value.before( now ) ) {
HibernateConstraintValidatorContext hibernateContext =
context.unwrap( HibernateConstraintValidatorContext.class );
hibernateContext.disableDefaultConstraintViolation();
hibernateContext.addExpressionVariable( "now", now )
.buildConstraintViolationWithTemplate( "Must be after ${now}" )
.addConstraintViolation();
return false;
}
return true;
}
}
The reference guide has some more details.