Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.validation How get property name in a validation message

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 "";
    }
}
like image 875
lenilsondc Avatar asked Jun 12 '15 17:06

lenilsondc


1 Answers

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."

like image 185
DavidS Avatar answered Nov 15 '22 00:11

DavidS