抱歉,如果这个问题之前已在某处讨论过。如果有请给我链接,我还没有找到满意的答案。
我一直在寻找一种方法,让 javax 验证提供的错误消息更加具体。
我当前的 @Min 注释消息在 ValidationMessages.properties 文件中指定:
javax.validation.constraints.Min.message=The value of this variable must be less than {value}.
这会按预期打印出来
The value of this variable must be less than 1
我想要的是该消息还包括验证失败的变量(和类)的名称以及失败的变量的值。所以更像。
The value of class.variable was 0 but not must be less than 1
任何帮助将不胜感激。
Klee
嗯。恼人的!在我看来,你有 3 个选择:
你可以写一个自定义的消息插值器并将其替换到您的验证配置中,但这似乎非常脆弱。
您可以以 @Min 的风格声明您自己的自定义注释(请参阅此处如何进行自定义验证器) ...
..但是您需要的信息实际上保存在来自 Validator 实例的 ConstraintViolation 对象中。只是它没有被放入默认消息中。
我猜您目前正在使用某种网络框架来验证表单。如果是这种情况,那么覆盖验证并执行类似的操作应该非常简单(快速 hacky 版本,您应该能够通过使用外部属性文件使这变得非常整洁):
Set<ConstraintViolation<MyForm>> violations = validator.validate(form);
for (ConstraintViolation<MyForm> cv : violations) {
Class<?> annoClass = cv.getConstraintDescriptor().getAnnotation().getClass();
if (Min.class.isAssignableFrom(annoClass)) {
String errMsg = MessageFormat.format(
"The value of {0}.{1} was: {2} but must not be less than {3}",
cv.getRootBeanClass(),
cv.getPropertyPath().toString(),
cv.getInvalidValue(),
cv.getConstraintDescriptor().getAttributes().get("value"));
// Put errMsg back into the form as an error
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)