使javax验证错误消息更具体

使javax验证错误消息更具体,java,bean-validation,min,Java,Bean Validation,Min,对不起,如果这个问题以前在什么地方讨论过。如果有,请联系我,我还没有找到一个满意的答案 我一直在四处寻找,试图找到一种方法,使javax验证提供的错误消息更加具体 在ValidationMessages.properties文件中指定了我当前用于@Min注释的消息: javax.validation.constraints.Min.message=The value of this variable must be less than {value}. Set<ConstraintVio

对不起,如果这个问题以前在什么地方讨论过。如果有,请联系我,我还没有找到一个满意的答案

我一直在四处寻找,试图找到一种方法,使javax验证提供的错误消息更加具体

在ValidationMessages.properties文件中指定了我当前用于@Min注释的消息:

javax.validation.constraints.Min.message=The value of this variable must be less than {value}.
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 } } 这张照片会像预期的那样打印出来

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

我认为您需要创建自定义约束。
您没有提到您正在使用的规范的哪个实现,但是有关于如何为Hibernate验证器创建自定义约束的很好的文档


该过程的一部分将涉及创建您自己的ValidationMessages.properties文件。烦人!在我看来,您有3种选择:

  • 您可以编写一个自定义代码并将其替换到验证配置中,但这似乎非常脆弱

  • 您可以以@Min()的样式声明自己的自定义注释

  • 。。但是您需要的信息实际上保存在来自验证器实例的ConstraintViolation对象中。只是它没有被放入默认消息中

  • 我猜您目前正在使用某种web框架来验证表单。如果是这种情况,那么覆盖验证并执行类似操作应该非常简单(quick hacky版本,您应该能够通过使用外部属性文件使其非常整洁):

    设置冲突=validator.validate(表单); 对于(约束约束cv:违规){ 类annoClass=cv.getConstraintDescriptor().getAnnotation().getClass(); if(最小类isAssignableFrom(annoClass)){ 字符串errMsg=MessageFormat.format( “{0}.{1}的值为:{2},但不得小于{3}”, cv.getRootBeanClass(), cv.getPropertyPath().toString(), cv.getInvalidValue(), cv.getConstraintDescriptor().getAttributes().get(“值”); //将errMsg作为错误放回表单中 } }