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.
You can perform validation with Errors/BindingResult object. Add Errors argument to your controller method and customize the error message when errors found. Below is the sample example, errors. hasErrors() returns true when validation is failed.
A custom validation annotation can also be defined at the class level to validate more than one attribute of the class. A common use case for this scenario is verifying if two fields of a class have matching values.
The Javax bean validation API provides the following most frequently used annotations. The Hibernate validator provides the following commonly used annotations for validation. In case of product or project development we must use both the annotations for bean validation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With