Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize spring validation error

I want customize the spring validation error for

    @NotNull     @Length(max = 80)     private String email;  

but I'm unable to do it. What are the step to follow?

like image 515
Roberto de Santis Avatar asked Jan 26 '11 13:01

Roberto de Santis


People also ask

What is the use of MessageSource in Spring?

Overview. MessageSource is a powerful feature available in Spring applications. This helps application developers handle various complex scenarios with writing much extra code, such as environment-specific configuration, internationalization or configurable values.

What is custom validation in Spring MVC?

It is necessary to validate user input in any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side.


1 Answers

The JSR 303 default message interpolation algorithm allows you to customize messages by supplying a resource bundle named ValidationMessages. Create a ValidationMessages.properties file in the classpath containing:

javax.validation.constraints.NotNull.message=CUSTOM NOT NULL MESSAGE javax.validation.constraints.Size.message=CUSTOM SIZE MESSAGE 

This changes the default message for the @Size constraint, so you should use the @Size constraint instead of the Hibernate-specific @Length constraint.

Instead of changing the default message for all constraints, you can change the message for a specific constraint instance. Set the message attribute on the constraint:

@NotNull(message = "{email.notnull}") private String email; 

And add the message to the ValidationMessages.properties file:

email.notnull=E-mail address is required 
like image 147
Chin Huang Avatar answered Sep 30 '22 00:09

Chin Huang