Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bean validation - override default message

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.
like image 609
djmj Avatar asked Dec 11 '22 14:12

djmj


1 Answers

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();
like image 55
Hardy Avatar answered Dec 28 '22 06:12

Hardy