javaspringspring-bootvalidationjavax.validation

Java validation: Cannot interpolate field name in validation message


I tried the approach mentioned on How get property name in a validation message, but cannot apply it to the following situation.

@Data
public class CompanyRequest {

    @PositiveOrZero(message = "validation.amount.positiveOrZero")
    int quantity;

    // code omitted for brevity

}

Here is my *.properties file having message:

validation.amount.positiveOrZero=The ${fieldName} value must be positive or zero

So, how can I use the property name in the validation message?


Solution

  • ${fieldName} could not be retrieved easily inside the annotation without major modifications inside the core mechanism that makes the evaluation.

    An easier way to achieve what you want, considering that for each field the name would be different, is the following.

    Inside properties file put the property

    validation.amount.positiveOrZero= value must be positive or zero
    

    And then define the annotation in the code as

    @PositiveOrZero(message = "The quantity {validation.amount.positiveOrZero}")
    int quantity;
    

    Edit: It seems that the property should not be defined in a simple application.properties file but in another file named ValidationMessages.properties in the classpath.

    As documented here

    setValidationMessageSource(MessageSource messageSource) Specify a custom Spring MessageSource for resolving validation messages, instead of relying on JSR-303's default "ValidationMessages.properties" bundle in the classpath.