• Spring MVC Custom Validation Messages

    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

    Spring MVC Custom Validation Messages

    Basically, you will just set your message resource bean in spring, and add that in your context.

    Spring MVC Custom Validation Messages Example

    This is a continuation of the tutorial Custom Validator in Spring MVC

    1. Create Property file for Messages

      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 {};
      }
      
    2. Edit your Servlet Dispatcher

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


      And in your bean for validator, add the property validationMessageSource with reference to the created messageSource above.

      
              <property name="validationMessageSource" ref="messageSource"/>
      
      
    3. Testing the Custom Messages

      And that’s it, its just easy to setup spring mvc custom validation messages.
      Here is the screenshot of the test:

      spring mvc custom validation messages

      spring mvc custom validation messages


      You can download the source code here: custom-validator-messages-example

    Related Post