How to add custom error messages in Hibernate validator

nash picture nash · Aug 17, 2011 · Viewed 32.2k times · Source

I have a simple class like this,

import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;

public class Form implements Serializable {
   @NotNull
   @Length(min = 2, max = 20)
   private String lastName;
}

I have messages.properties file in the classpath. It's then loaded via Spring bean as follows,

<bean name="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
        <ref bean="resourceBundleLocator"/>
    </property>
</bean>

<bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>classpath*:messages.properties</value>
        </list>
    </property>
</bean>

All I want is to get error messages customized according to the bean validated. In other words I want to have each ConstraintViolation object return the error message I have defined in my property file instead of the default one. Is it possible to add message property with a value like this format {xxx.yyyy.zzzz} and refer that message from the messages.properties file ?

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Form>> inputErrors = validator.validate(form); 

If I want to customize the default message for @NotNull and @Length, how can I do that?

My experience on Hibernate validation is zero, Any sample code or step by step guide would be appreciated.

Answer

stereoscope picture stereoscope · Aug 17, 2011

You have this resource bundle file holding the message values.

I think you have to use the path to the i.e. @NotNull annotation to override the message by hand! like javax.validation.constraints.NotNull=Notnull error happened! or something like that!

Look here for that :

Hibernate Validator - The error message

Hope that helps