Javax.validation How to get property name in validation message

I'm looking for the correct way to use the property name in validation messages like {min}

or {regexp}

.

I have googled this question several times already and apparently there is no native method for this.

@NotNull(message = "The property {propertyName} may not be null.")
private String property;

      

Has anyone encountered this before and managed to find a solution for this?

UPDATE 1

Using a custom post interpolator should be something like this:

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 "";
    }
}

      

+5


source to share


1 answer


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 the message resource file:



error.notblank.part1of2=The following field must be supplied: '
error.notblank.part2of2='. Correct and resubmit.

      

When the check fails, it displays the message "The following field should be checked:" Address line 1 ". Correct and resend."

+3


source







All Articles