I\'ve written a validation annotation implemented by a custom ConstraintValidator
. I also want to generate very specific ConstraintViolation
objects th
If you use message codes you can simply add something like {0} in them.
For example: "The field {0} must not be empty."
And then use hibernateContext.addMessageParameter("0", fieldName);
instead of addExpressionVariable(...)
.
That worked for me.
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<Future, Date> {
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.