4

如何在类级别验证器上返回不同的消息?

界面

public @interface ValidFoo
{
    public String message() default "{package.ValidFoo.message}";
}

执行

@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.
4

1 回答 1

13

您需要使用ConstraintValidatorContext来选择正确的消息模板。您可以在 Hibernate Validator 文档中看到一个示例 - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints-validator

实际上,您可以执行以下操作:

    constraintContext.disableDefaultConstraintViolation();
    constraintContext.buildConstraintViolationWithTemplate(
            "{package.ValidFoo.message_constraint1}" 
    )
    .addConstraintViolation();
于 2013-06-05T08:21:26.270 回答