5

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.