Reputation: 9800
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 "";
}
}
Upvotes: 10
Views: 5263
Reputation: 12032
As another workaround, you may also pass the property name to the message text as shown below:
Add the validation message to the properties file (e.g. text.properties):
javax.validation.constraints.NotNull.message=may not be null.
Then define the annotation in the code as shown below:
@NotNull(message = "propertyName {javax.validation.constraints.NotNull.message}")
private String property;
Upvotes: 0
Reputation:
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."
Upvotes: 6