1

In my Spring MVC application I'm making use of @Validated objects in my controllers, using JSR-303. In my Spring application context I have defined a custom MessageSource, to read messages from a resources/messages.properties file.

I'm able to read and override javax.validation default messages (such as NotNull), but I get an error if I try to use message interpolation to read a parameter (e.g.: min or max from @Size(max=...).

Note that if I set a message directly in my model, it correctly shows the "interpolated" message (default message works fine too).

Model class:

    public class Customer {

            @JsonProperty("name")
            @NotNull
            @Size(max = 50) // if I add message = "This field must be less than {max} characters long" it works!
            private String name;

            // Other fields here + getters and setters
    }

messages.properties:

Size=This field must be less than {max} characters long
NotNull=This field must be set.
user3673449
  • 347
  • 2
  • 5
  • 20

2 Answers2

0

Solved it by using positional parameters instead of named ones (not sure why they don't work though).

Size=This field must be less than {1} characters long
user3673449
  • 347
  • 2
  • 5
  • 20
0

If you want to have more control over the messages, ex. different messages for different classes, you can try with this approach

    @NotBlank(message = "{product.name.blank}")
    @Size(min = 2, message = "{product.name.minsize}")
    @ApiModelProperty(value = "Product Name", required = true, example = "Jabuke", position = 0)
    private String name;

You store messages in the ValidationMessages.properties instead of the application.properties. It is automatically loaded into context.

product.name.blank=Product name can not be blank
product.name.minsize=Product name must be 2 characters or more