如何在类级别验证器上返回不同的消息?
接口
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.
答案 0 :(得分:10)
您需要使用 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();