This example will show you on how to add your custom validation messages. This assumes that you have basic knowledge in validators or if not, read first Spring MVC Form Validation
Basically, you will just set your message resource bean in spring, and add that in your context.
This is a continuation of the tutorial Custom Validator in Spring MVC
Create a property file in your resources folder and add the key-value pair for the validator’s messages. Here is an example of our messages.properties:
org.hibernate.validator.constraints.NotEmpty.message=the field cannot be empty com.javapointers.customvalidator.validator.NotExistingUsername.message=username already used
To overwrite the default message for the existing validator, add a key-value pair to your messages.properties. The key is in format:
<package-name>.<interface>.message
So for example, for @NotEmpty validator, the key should be:
org.hibernate.validator.constraints.NotEmpty.message
Also, if you have created your own custom validator, follow the key convention and in your custom validator interface, set the default message to your key inside a bracket. For example, in the interface NotExistingUsername:
public @interface NotExistingUsername { String message() default "{com.javapointers.customvalidator.validator.NotExistingUsername.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
Define the bean for your messageSource. For example, if you have messages.properties inside your resource folder, then it will look like this:
<property name="basename" value="messages"/>
<property name="validationMessageSource" ref="messageSource"/>
And that’s it, its just easy to setup spring mvc custom validation messages.
Here is the screenshot of the test: