10

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 "";
    }
}
lenilsondc
  • 9,590
  • 2
  • 25
  • 40
  • You can always write a custom annotation that checks for null value and takes some property. – Branislav Lazic Jun 12 '15 at 18:03
  • Sure, i thought about this, but not sure if is best choice. Once is not about a new annotation for checking null values. I'm thinking about some way to create generic messages, preventing create a bunch of validation messages one for each property. I've read about MessageInterpolator interface, but still don't know how use it. – lenilsondc Jun 12 '15 at 18:12

2 Answers2

6

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

DavidS
  • 5,022
  • 2
  • 28
  • 55
  • 1
    Good solution. Apparently there is no way to intercept property name on `MessageInterpolator.Context`. Anyway, thank you all, for your answers and comments. If i find one solution of this nature, i'll share with you. Thanks – lenilsondc Jun 15 '15 at 11:13
0

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;

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63