Thursday, 8 August 2013

Spring Form Validation Example


Here is one simple example to validate form (Student form). Spring API providers Validator interface to implement form validations. To implement validation we have to create a validator class which implements the Validator interface and should override validate() method. In this example i am going to validate two text field for Student form

1. Create a Validator class

Create a dynamic web project in Eclipse and add all spring mvc related jars in the web/lib folder, see this example for more details (Spring MVC Example). Once we created the web application create a Validator class.

package com.pretech;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.pretech.Student;
public class StudentValidator implements Validator {
	public boolean supports(Class<?> clazz) {
		return Student.class.isAssignableFrom(clazz);
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
		ValidationUtils.rejectIfEmpty(errors, "address", "address.required");
		Student student = (Student) target;

2. Add Validator details into dispatcher-servlet.xml

<bean id="StudentValidator" class="com.pretech.StudentValidator" />


Create and placed in to src folder with below properties

name.required = Student Name should not be blank
address.required = Student Address should not be blank

Add below Message Resources in despatcher-servlet.xml file

<bean id="messageSource" class="" p:basename="messages" />

4. Add Validator reference to the bean which we are going to validate

<bean name="/studentRegistration.htm" class="com.pretech.StudentController"
  p:formView="StudentDetails" p:successView="SuccessPage" p:validator-ref="StudentValidator" />

5. Add form error details in to JSP page to display

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Registration Page</title>
.error {
color: #ff0000;
font-style: italic;
<form:form method="POST" commandName="student">
			<td>Enter Student Name :</td>
			<td><form:input path="name" /></td>
			<td><form:errors path="name" cssClass="error" /></td>
			<td>Enter Student Address :</td>
			<td><form:input path="address" /></td>
			<td><form:errors path="address" cssClass="error" /></td>
			<td colspan="3"><input type="submit" value="Register"></td>

6. Deploy and run application

To test the validator click on Register button without any values


7. Download Example

Spring MVC Form Validation Example