How do I implement multiple JSR-303 validation messages for the same @Constraint?
I am using JSR-303 (hibernate-validator) on an entity with several different rules to be applied. Rather not stack multiple annotations @Constraint
for them and instead use one for example. @MyEntityConstraint
...
The problem is that there should indeed be a different message on each type of validation error, but the message seems inextricably linked to the annotation:
public @interface MyEntityConstraint {
String message() default "A single, unchangeable message per constraint???";
// ...
}
Is there a way around this or am I doomed to have:
@MyEntityConstraint1
@MyEntityConstraint2
// ...
@MyEntityConstraintn
@Entity
public class MyEntity {
// ...
}
source to share
Have a look at the ConstraintValidatorContext passed to isValid
your constraint validator method . It allows you to customize error messages that involve using different message templates depending on your validation state.
source to share
As suggested by Hardy, this can be done quite simply using the ConstraintValidatorContext - as shown below:
@Override
public boolean isValid(MyEntity myEntity, ConstraintValidatorContext context) {
// Disable default ConstraintViolation so a customised message can be set instead.
context.disableDefaultConstraintViolation();
return checkConstraint1(myEntity, context)
&& checkConstraint2(myEntity, context)
//...
&& checkConstraintn(myEntity, context);
}
// Note: A private method for each constraint decreases the cyclomatic complexity.
private boolean checkConstraint1(MyEntity myEntity, ConstraintValidatorContext context) {
// Default validity is true until proven otherwise.
boolean valid = true;
if (/*<<Insert constraint #1 conditions (about myEntity) here>>*/) {
valid = false;
context.buildConstraintViolationWithTemplate(
"<<Insert constraint #1 failure message here>>").addConstraintViolation();
}
return valid;
}
source to share