2

我有我的自定义validator,我想为它添加一些错误消息。所以我有下一个代码:

@Override
public boolean isValid(final String label,
                       final ConstraintValidatorContext constraintValidatorContext) {
     constraintValidatorContext.disableDefaultConstraintViolation();

     if(label.length() > MAX_LENGTH) {
          constraintValidatorContext
                  .buildConstraintViolationWithTemplate("{error.maxLength}")
                  .addConstraintViolation();
          return false;
     }
     ...
}

我的消息看起来像error.maxLength=You have exceeded max length of {0},所以它的参数是maxLength.

在构建约束违规时可以添加它吗?

4

1 回答 1

9

是的你可以。

您必须使用以下方法打开ConstraintValidatorContext包装HibernateConstraintValidatorContext

HibernateConstraintValidatorContext hibernateConstraintValidatorContext = constraintValidatorContext.unwrap( HibernateConstraintValidatorContext.class );

然后,您可以使用:

hibernateConstraintValidatorContext.addMessageParameter("name", value);

(你的看起来像一个消息参数({variable})所以它可能是你必须使用的 - 注意你需要 HV 5.4.1.Final 有这个方法)

或者

hibernateConstraintValidatorContext.addExpressionVariable("name", value);

如果它是一个表达式变量(所以使用表达式语言和类似的东西${variable}

于 2017-08-04T16:08:01.593 回答