Making javax validation error message more specific

柔情痞子 提交于 2019-11-30 12:06:38

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

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

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

  3. .. 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.

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

I believe you need to create a custom constraint.
You haven't mentioned which implementation of the spec you are using, but there is good documentation on how to create a custom constraint for the Hibernate Validator here.

Part of the process will involve creating your own ValidationMessages.properties file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!