Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Custom Validator - Interpolate message with parameter

Tags:

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.

like image 450
Blease Avatar asked Jan 17 '19 08:01

Blease


1 Answers

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.

like image 167
Guillaume Smet Avatar answered Oct 05 '22 01:10

Guillaume Smet