DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Form Validation Tutorial

Spring Form Validation Tutorial

Meyyappan Muthuraman user avatar by
Meyyappan Muthuraman
·
Jun. 15, 12 · Tutorial
Like (1)
Save
Tweet
Share
177.14K Views

Join the DZone community and get the full member experience.

Join For Free

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
Form (document) Spring Framework Property (programming)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Quick Pattern-Matching Queries in PostgreSQL and YugabyteDB
  • Building a Scalable Search Architecture
  • Utilize OpenAI API to Extract Information From PDF Files
  • Why It Is Important To Have an Ownership as a DevOps Engineer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: