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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With