我有我的自定义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的参数。
是否可以在构建约束冲突时添加它?
发布于 2017-08-04 16:08:01
可以,停那儿吧。
您必须使用以下内容将ConstraintValidatorContext解压缩到HibernateConstraintValidatorContext:
HibernateConstraintValidatorContext hibernateConstraintValidatorContext = constraintValidatorContext.unwrap( HibernateConstraintValidatorContext.class );然后,您可以使用:
hibernateConstraintValidatorContext.addMessageParameter("name", value);(您的文件看起来像一个消息参数({variable}),所以这可能是您必须使用的-注意,您需要HV5.4.1,最后才有此方法)
或
hibernateConstraintValidatorContext.addExpressionVariable("name", value);如果它是一个表达式变量(所以使用表达式语言和类似于${variable}的东西)
https://stackoverflow.com/questions/45510986
复制相似问题