I'm looking for a proper way to use property name inside validation messages, like {min}
or {regexp}
.
I've googled this question a few times now and apparently there isn't a native method for doing this.
@NotNull(message = "The property {propertyName} may not be null.")
private String property;
Has anyone experienced this before and has managed to find a solution for this?
UPDATE 1
Using a custom message interpolator should be something like:
public class CustomMessageInterpolator implements MessageInterpolator {
@Override
public String interpolate(String templateString, Context cntxt) {
return templateString.replace("{propertyName}", getPropertyName(cntxt));
}
@Override
public String interpolate(String templateString, Context cntxt, Locale locale) {
return templateString.replace("{propertyName}", getPropertyName(cntxt));
}
private String getPropertyName(Context cntxt) {
//TODO:
return "";
}
}
One solution is to use two messages and sandwich your property name between them:
@NotBlank(message = "{error.notblank.part1of2}Address Line 1{error.notblank.part2of2}")
private String addressLineOne;
Then in your message resource file:
error.notblank.part1of2=The following field must be supplied: '
error.notblank.part2of2='. Correct and resubmit.
When validation fails, it produces the message "The following field must be supplied: 'Address Line 1'. Correct and resubmit."
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