Meyyappan has posted 101 posts at DZone. View Full User Profile

Spring Form Validation Tutorial

06.15.2012
| 81760 views |
  • submit to reddit

In this example you will see how to validate the user registration form that we created in the previous example. To validate the form fields all you need to do is to have a seperate UserValidator class that implements the Validator interface, override the validate() method perform all the validations. In the jsp page add form:errors tag to dispaly errors and finally you need to link the UserValidator class with the UserController class. Since the UserController class extends the SimpleFormController class the validate() method will be called automatically. Incase you would like to have the error messages in a seperate properties file then you need to create a new properties file, add all the error keys and its corresponding values and finally link it to Spring configuration file.

Here is our UserValidator class.

package com.vaannila.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.vaannila.domain.User;

public class UserValidator implements Validator {

	@Override
	public boolean supports(Class<?> clazz) {
		return User.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
		ValidationUtils.rejectIfEmpty(errors, "gender", "gender.required");
		ValidationUtils.rejectIfEmpty(errors, "country", "country.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aboutYou", "aboutYou.required");
		User user = (User) target;
		if(user.getCommunity().length == 0)
		{
			errors.rejectValue("community","community.required");
		}
	}

}

Here you need to override the validate method. To check mandatory condition you can use the ValidationUtils class methods like rejectIfEmptyOrWhitespace or rejectIfEmpty. These methods takes three arguments the Errors object, the property name, and the error code. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly. To do any other validation you have access to the domain object, using the domain object validate the properties, incase there are errors you can use the rejectValue() method of the Errors class to add errors. Here the first argument is the property name and the second argument is the error code.

The messages.properties file contains the following error keys and values.

name.required = User Name is required
password.required = Password is required
gender.required = Gender is required
country.required = Country is required
aboutYou.required = About You is required
community.required = Select at least one community

 Now add the form:errors tags in the jsp page to display the errors.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Registration Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>

<form:form method="POST" commandName="user">
<table>
    <tr>
        <td>User Name :</td>
        <td><form:input path="name" /></td>
        <td><form:errors path="name" cssClass="error" /></td>
    </tr>
    <tr>
        <td>Password :</td>
        <td><form:password path="password" /></td>
        <td><form:errors path="password" cssClass="error" /></td>
    </tr>
    <tr>
        <td>Gender :</td>
        <td><form:radiobutton path="gender" value="M" label="M" /> 
            <form:radiobutton path="gender" value="F" label="F" /></td>
        <td><form:errors path="gender" cssClass="error" /></td>	
    </tr>
    <tr>
        <td>Country :</td>
        <td><form:select path="country">
            <form:option value="" label="Select" />
            <form:option value="1" label="India" />
            <form:option value="2" label="USA" />
            <form:option value="3" label="UK" />
        </form:select></td>
        <td><form:errors path="country" cssClass="error" /></td>
    </tr>
    <tr>
        <td>About you :</td>
        <td><form:textarea path="aboutYou" /></td>
        <td><form:errors path="aboutYou" cssClass="error" /></td>
    </tr>
    <tr>
        <td>Community :</td>
        <td><form:checkbox path="community" value="Spring" label="Spring" /> 
        <form:checkbox path="community" value="Hibernate" label="Hibernate" /> 
        <form:checkbox path="community" value="Struts" label="Struts" /></td>
        <td><form:errors path="community" cssClass="error" /></td>
    </tr>
    <tr>
        <td colspan="3"><form:checkbox path="mailingList"
            label="Would you like to join our mailinglist?" /></td>
    </tr>
    <tr>
        <td colspan="3"><input type="submit" value="Register" ></td>
    </tr>
</table>
</form:form>

</body>
</html>

The path attribute of the form:errors tag indicate the property for which the error should be displayed. Use path="*" to display all the errors together.

In the Spring configuration file, link the UserValidator with the UserController using the validator-ref property and add the properties file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="viewResolver"
          class="org.springframework.web.servlet.view. InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

    <bean id="messageSource" class="org.springframework.context.support. ResourceBundleMessageSource" p:basename="messages" />

    <bean id="userService" class="com.vaannila.service.UserServiceImpl" />

    <bean id="userValidator" class="com.vaannila.validator.UserValidator" />

	<bean name="/userRegistration.htm" class="com.vaannila.web.UserController" p:userService-ref="userService" p:formView="userForm" p:successView="userSuccess" p:validator-ref="userValidator" />

</beans>

 The directory structure of the example is show below. The messages.properties file should be placed in the root of the classpath.

 Run the example. Click the Register button without filling any details. You will see the following error messages.

 

You can download and try the example here.

Source :Download
War :Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: