Spring Custom Validator - Interpolate message with parameter

问题: I've created a custom ConstraintValidator where the isValid method looks like this: private String message; @Override public void initialize(InputValidator constraintAnn...

问题:

I've created a custom ConstraintValidator where the isValid method looks like this:

private String message;

@Override
public void initialize(InputValidator constraintAnnotation) {
    this.message = constraintAnnotation.message();
}

@Override
public boolean isValid(String inputValue, ConstraintValidatorContext context) {
    HibernateConstraintValidatorContext h = context.unwrap(HibernateConstraintValidatorContext.class);
    h.disableDefaultConstraintViolation();

    //logic goes here

    if(!valid) {
        h.addExpressionVariable("0", inputValue);
        h.buildConstraintViolationWithTemplate(this.message)
            .addConstraintViolation();
    }
    return valid;
}

I also have the following in messages.properties:

error.input=The value {0} is invalid.

I can use the above message and substitute the {0} value within when using it within thymeleaf and with a MessageSource bean, however the HibernateConstraintValidatorContext will not substitute the value.

Given the constraints of my project I cannot change the message format e.g. changing it to The value ${0} is invalid..

I currently have the application showing the response "The value userInput is invalid." where "userInput" is the name of the field in the form/object.


回答1:

So {0} is a message parameter while ${0} is an expression variable.

You have to use #addMessageParameter() instead of #addExpressionVariable(). It was introduced in Hibernate Validator 5.4.1 but you should upgrade anyway if you use an older version.

  • 发表于 2019-01-18 20:05
  • 阅读 ( 237 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除