Form Validation – part 1 ( using JSR 303_349 annotations )

Using @Validate and @Size annotation for validation

In Spring MVC to perform Validation we have to use a Third Party Library for this purpose.

The most commonly used Jars used in Spring are from Hibernate.
You can get these files downloaded from below location.

http://hibernate.org/validator/downloads/

After you download add below jars to lib directory of your application.

For our example we would require below jars

  1. hibernate-validator-5.2.4.Final.jar
  2. classmate-1.1.0.jar
  3. jboss-logging-3.2.1.Final.jar
  4. validation-api-1.1.0.Final.jar

Now suppose we have a requirement that in our RegistrationForm for the Hobby field the user should enter min 5 character and max 25 character.

Then we need to make below changes in our application to achieve this.

Add the corresponding import  statements in Student.java and StudentRegistrationController.java

import javax.validation.constraints.Size;
import javax.validation.Valid;

We need to add @Valid annotation in our Controller class  method as below

@RequestMapping(value=”/submitRegistrationForm.html”, method = RequestMethod.POST)
public ModelAndView submitRegistrationForm(@Valid @ModelAttribute(“student1”) Student student1,BindingResult result) {
if(result.hasErrors()){
ModelAndView model = new ModelAndView(“RegistrationForm”);
return model;

}
ModelAndView model = new ModelAndView(“RegistrationSuccess”);
return model;
}

Another change that is required is in the Student.java file ,we need to add the below annotation for which we want to validate.

@Size(min=3, max=25)
private String studentHobby;

After this  when you run the application and in your RegistrationForm

validation1

Next,enter text in hobby field ,less then 5 character like above and submit the form.

validation2

A validation message would be displayed on your RegistrationForm page

“size must be between 3 and 25”


   

Comments are closed