I have my custom validator
and I want to add some error messages for it.
So I have next code:
@Override
public boolean isValid(final String label,
final ConstraintValidatorContext constraintValidatorContext) {
constraintValidatorContext.disableDefaultConstraintViolation();
if(label.length() > MAX_LENGTH) {
constraintValidatorContext
.buildConstraintViolationWithTemplate("{error.maxLength}")
.addConstraintViolation();
return false;
}
...
}
My message looks like error.maxLength=You have exceeded max length of {0}
, so it has parameter of maxLength
.
It it possible to add it when building constraint violation?
Yes, you can.
You have to unwrap the ConstraintValidatorContext
to an HibernateConstraintValidatorContext
with:
HibernateConstraintValidatorContext hibernateConstraintValidatorContext = constraintValidatorContext.unwrap( HibernateConstraintValidatorContext.class );
Then, you can either use:
hibernateConstraintValidatorContext.addMessageParameter("name", value);
(and yours look like a message parameter ({variable}
) so it's probably what you have to use - note you need HV 5.4.1.Final to have this method)
or
hibernateConstraintValidatorContext.addExpressionVariable("name", value);
if it's an expression variable (so using Expression Language and something like ${variable}
)