How can I return different messages on a class level validator?
Interface
public @interface ValidFoo
{
public String message() default "{package.ValidFoo.message}";
}
Implementation
@Override
public boolean isValid(final Foo foo, final ConstraintValidatorContext context)
{
// check constraint 1
// --> return message "package.ValidFoo.message_constraint1"
// check constraint 2
// --> return message "package.ValidFoo.message_constraint2"
}
ValidationMessages.properties
package.ValidFoo.message=Validation error.
package.ValidFoo.message_constraint1=Validation error 1.
package.ValidFoo.message_constraint2=Validation error 2.
You need to use the ConstraintValidatorContext to select the right message template. You can see an example in the Hibernate Validator docs - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints-validator.
Effectively you do something like:
constraintContext.disableDefaultConstraintViolation();
constraintContext.buildConstraintViolationWithTemplate(
"{package.ValidFoo.message_constraint1}"
)
.addConstraintViolation();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With