使javax验证错误消息更具体 [英] Making javax validation error message more specific

查看:154
本文介绍了使javax验证错误消息更具体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果以前某个地方已经涵盖了这个问题。如果它已经链接到我,我还没有找到一个满意的答案。

Sorry if this question has been covered somewhere before. If it has please link me to it, I haven't been able to find a satisfactory answer as yet.

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

I've been looking around trying to find a way to have the error messages provided by my javax validation more specific.

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

The message I currently have for my @Min annotation is specified in the ValidationMessages.properties file:

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

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

What I would like to have is the message also include the name of the variable (and class) that has failed the validation as well as the value of the variable that failed. So more like.

The value of class.variable was 0 but not must be less than 1

任何帮助将不胜感激。

Any help would be greatly appreciated.

Klee

推荐答案

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

Hmmm. Annoying! As I see it you have 3 options:


  1. 你可以写一个自定义 MessageInterpolator 并将其替换为验证配置,但这似乎很脆弱。

  1. You could write a custom MessageInterpolator and substitute it into your validation configuration, but that's seems really brittle.

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

You could declare your own custom annotation in-the-style of @Min (see how to do a custom validator here) ...

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

.. But the information you need is actually held within the ConstraintViolation object that comes out of the Validator instance. It's just that it doesn't get put into the default message.

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

I'm guessing you're currently using some kind of web framework to validate a form. If that's the case, it should be quite straightforward to override the validation and do something like this (quick hacky version, you should be able to make this very tidy by using an external properties file):


  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 
    }
  }

这篇关于使javax验证错误消息更具体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆