Spring MVC Fast Tutorial: Form Validation

What are we going to build?

User input validation for the new car form.

Validator

This Validator class will validate a Car: 'WEB-INF/src/springmvc/validator/CarValidator.java'

package springmvc.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
 
import springmvc.model.Car;
 
public class CarValidator implements Validator {
 
	public boolean supports(Class aClass) {
		return Car.class.equals(aClass);
	}
 
	public void validate(Object obj, Errors errors) {
		Car car = (Car) obj;
 
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "model", "field.required", "Required field");
 
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "field.required", "Required field");
		if ( ! errors.hasFieldErrors("price")) {
			if (car.getPrice().intValue() == 0)
				errors.rejectValue("price", "not_zero", "Can't be free!");
		}		
	}
}
  • supports(): declare classes supported by this validator
  • To add an error these parameters are needed:
    • Car field name
    • error message key
    • default message if no message is not found for the key

View

Let's update the view 'jsp/carNew.jsp':

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 
<html>
 
<head>
  <title>New Sponsor</title>
  <style>
    .error {
    	color: red;
    }
  </style>  
</head>
 
<body>
	<h1>New Car</h1>
 
	<form:form method="post">
 
		Brand<br />
		<form:select path="brand">
		   <form:options items="${brandList}" itemLabel="name" itemValue="id" />
		</form:select>
		<br /><br />
 
		Model <form:errors path="model" cssClass="error"/><br />
		<form:input path="model"/><br /><br />
 
		Price <form:errors path="price" cssClass="error"/><br />
		<form:input path="price"/><br /><br />
 
		<input type="submit" value="Submit">
 
	</form:form>
</body>
</html>

Configuration

We now declare the validator for the URL addCar.html in 'WEB-INF/springmvc-servlet.xml'

    <bean name="/new_car.html" class="springmvc.web.CarNewController">
        <property name="commandClass" value="springmvc.model.Car"/>
        <property name="formView" value="carNew"/>
        <property name="successView" value="list_cars.html"/>
		<property name="validator">
        	<bean class="springmvc.validator.CarValidator"/>
        </property>
    </bean>

Result

Build (ant) and relaunch Tomcat: http://localhost:8180/springmvc/new_car.html

We can check it's working by entering empty values:


Previous: Form Processing --- Up: Spring Fast Tutorial --- Next: Dependency Injection

 

Feedback

this is very good way to learn Spring but please can you do this tutorials with Net beans or Eclipse? this will be a great job thank you
Mahmou Morsi
July 23, 2008
#1
You can clearly see from the screen shots in earlier sections of the tutorial that Jérôme is using Eclipse. However I think he is doing a good job of hiding it as tutorials should be generic as possible. Not everybody uses NetBeans or Eclipse.

July 24, 2008
#2
Could you please describe what supports method do ?
sain
August 28, 2008
#3
great tutorial... kudos to u..
Goodguy
September 29, 2008
#4
thnks 4 the great tutorial!!!
ariesrana
October 1, 2008
#5
Because of you, I love Spring now!
Dmitry Bahtiarov
October 10, 2008
#6
Thanks for good tutorial.
Mr.A
October 12, 2008
#7
Why don't use use spring:bind tag?
Mr.A
October 12, 2008
#8
that was simply superb
Balaji Srikanth
November 25, 2008
#9
Exactly what I was looking for!

December 26, 2008
#10
Dubakoor material
johnson
February 17, 2009
#11
No downloads for this one?
saket jha
April 6, 2009
#12
This is excellent one ,but no download..
sanu
April 13, 2009
#13
it really good site from spring beginner . but when i am using <form:form></form:form> in my jsp. i am getting no such method error. any one can help me
sumadha
April 24, 2009
#14
best tutorial for beginning with spring, that i ever seen:)
y0y0
May 4, 2009
#15
Good Tutorial..
Bals
May 12, 2009
#16
Excellent Tutorial. Simple, yet covers most of the spring functionality.
Satish
May 26, 2009
#17
Spring bind tag is old when compared to the <form:tag> and the error messages are not displayed after validation when spring tag is used.
gomsz
June 4, 2009
#18
Its really superb tutorial for starting spring. Thanks a lot..
Avi
June 7, 2009
#19
Excellent!!! easy and funtional, very good, thanks!!!!

June 12, 2009
#20
Awsome, simple and clean, thanks very much!!!
tommmy
June 15, 2009
#21
Outstanding example for validation that i never ever seen this type of easiest understanding example thanks a lot for the people who introduced this example
VUMMADI MANOHAR REDDY
June 30, 2009
#22
thanks a lot for the example... really help ful :D but i have a little doubt.. wil this validation work in a ftl? in my case it didn't :(
farhath
July 3, 2009
#23
Lucid
:-)
July 9, 2009
#24
excellent tutorial
jaks
July 20, 2009
#25
yeah tutorial to mast hai !!!!
jasminder bhomra (jassi)
July 20, 2009
#26
It's simple excellent.The way you have presented the topic is superb.

July 31, 2009
#27
good one
sg
August 11, 2009
#28
Thanks again - very handy!
PUK
September 10, 2009
#29
This is most appropriate starters tutorial i have come across on the net for any technology. Thanks a lot Jérôme
Ajay
September 11, 2009
#30
Great tutorial. Much appreciated!!!
yupi
September 14, 2009
#31
Hi, if somebody types string in the field, you will receive exception (
pete
September 16, 2009
#32
Somebody knows how to handle the Exception if you put a String in the Price Field? the exceptions is shown in the <form:errors :(
aamc
October 15, 2009
#33
what happends if I put "rrrr" in price Value?? how can i get a custom message for this error??
aamc2
October 15, 2009
#34
Hi, i've solve the problem: you have to create a messages.properties file with: typeMismatch=invalid field typeMismatch.int=This value have to be integer typeMismatch.java.lang.Integer={0} have to be Integer. typeMismatch.java.util.Date={0} have to be Date, use format MM/dd/yyyy. and then map this in your application-context.xml with: messages That's all
aamc2
October 18, 2009
#35
I find framework in PHP...and fell in love with CodeIgnitor. I find framework in Java.. and fell in love with Spring. Thanks dude...
MSHW
October 25, 2009
#36
Great Tutorial. Quite Easy to understand and learn Spring. Many Thanks for your help in letting me grasp spring fundamentals in such a short time.
Praveen
November 10, 2009
#37
Really fantastic tutorial
rahul jain
December 22, 2009
#38
Is there a way to remove the added errors from the Errors object
kishore
December 28, 2009
#39
Hi, I'm adding all the field validation errors as follows errors.rejectValue(fieldName, errorCode) once i add the error based on some logic i want to remove the corresponding error from the 'errors'. How can i remove an added error from the errors object. I searched and not found any remove method on errors to remove the same. Can any one please help on this.
kishore
December 28, 2009
#40
nice tutorial. I liked it very much.
Ove
December 29, 2009
#41
Excellent Tutorial. Thank you
Venkata Madana
December 31, 2009
#42
Good stuff!
Anders Thøgersen
January 19, 2010
#43
Nice tutorial
siva
January 21, 2010
#44
xml is not valid. tag is not closed. Is it supposed to contain tag ?
Mircea
January 22, 2010
#45
Damn filterring.. I was talking about tag: lt property name eq "validator"

January 22, 2010
#46
Why is it new_car.html when the created page is jsp i.e.,carNew.jsp (http://localhost:8180/springmvc/new_car.html)
Deepa Revankar
January 29, 2010
#47
Very good material for beginers
Bhabatosh
February 2, 2010
#48
very pleased, thanks and keep going
yousef - opensoft
February 3, 2010
#49
Great simple tutorial for spring that leaves out all the other complex frameworks(eclipse,netbeans,maven,ant) that only confuse when learning. Thanks!
Kelvin
February 4, 2010
#50