使javax验证错误消息更具体

Kle*_*lee 11 java min bean-validation

对不起,如果这个问题已在某处提到过.如果有请链接我,我还没有找到一个满意的答案.

我一直在寻找一种方法让我的javax验证提供的错误消息更具体.

我目前拥有的@Min注释消息在ValidationMessages.properties文件中指定:

javax.validation.constraints.Min.message=The value of this variable must be less than {value}.
Run Code Online (Sandbox Code Playgroud)

这打印出来就像预期的那样

The value of this variable must be less than 1
Run Code Online (Sandbox Code Playgroud)

我想要的是消息还包括验证失败的变量(和类)的名称以及失败的变量的值.更像是.

The value of class.variable was 0 but not must be less than 1
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

克利

mil*_*use 14

嗯.烦!在我看来,你有3个选择:

  1. 您可以编写一个自定义的MessageInterpolator并将其替换为验证配置,但这看起来非常脆弱.

  2. 您可以在@Min的样式中声明自己的自定义注释(请参阅此处如何执行自定义验证器)...

  3. ..但您需要的信息实际上是在Validator实例中出现的ConstraintViolation对象中.只是它没有被置于默认消息中.

我猜你正在使用某种web框架来验证表单.如果是这种情况,那么覆盖验证并执行类似的操作应该非常简单(快速的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 
    }
  }