How to add custom error messages in the Hibernate validator

I have such a simple class,

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 a messages.properties file in the classpath. It then loads through the 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 configured according to the bean checked. In other words, I want each ConstraintViolation object to return an error message that I defined in my properties file, and not by default. Can I add a message property with a value similar to this format {xxx.yyyy.zzzz} and pass this 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 set a default message for @NotNull and @Length, how can I do this?

Hibernate . .

+5
1

, .

, i.e. @NotNull ! javax.validation.constraints.NotNull=Notnull error happened! - !

:

Hibernate Validator -

,

+4

All Articles