开发者

How to add custom error messages in Hibernate validator

开发者 https://www.devze.com 2023-03-29 05:19 出处:网络
I have a simple class like this, import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length;

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="re开发者_Python百科sourceBundleLocator"/>
    </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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号