Search code examples
springspring-mvcbean-validationhibernate-validator

Spring MVC + Hibernate validator : how can I override/internationalize the default error messages?


I'm working on a Spring MVC project in which I'm using Hibernate Validator to validate input fields from a form. As my project is Maven-based, I added this dependency:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator-annotation-processor</artifactId>
        <version>4.1.0.Final</version>
    </dependency>

The form validation process works fine but now, I would like to override or internationalize the default error messages.

For instance, by default, using the @NotEmpty annotation will yield the message "may not be empty". How I can replace this message by my own message? I've tried several solutions:

  • defining a Spring bean with id "messageSource" and setting its "basenames" property
  • creating ValidationMessages.properties file in the project classpath

But the default messages are still displayed...

Any hint? Thx in advance.


Solution

  • Yes you can do that. You can load the error message from the properties files. But you need to have the key in a proper format. Like NotEmpty.ClassName.fieldName=fieldName Can not be empty.

    You just need to specify your exact class name and property name in your properties files. Everything other is looking just perfect in your case.

    You can also have a common error message for a particular type of validation annotation for all the fields having that annotation. Like javax.validation.constraints.NotNull=Notnull erro happened!

    Hope this helps you. Cheers.