Spring MVC Fast Tutorial: Validating a form

What are we going to build?

We are going to add validation rules to the car creation form. When the form is submitted, if some data is invalid, we will display the form again with some error messages:

Add validation rules to the domain class

Add these Maven dependencies to the pom.xml file:

<!-- Java validation API -->
<dependency>
	<groupId>javax.validation</groupId>
	<artifactId>validation-api</artifactId>
	<version>1.1.0.Final</version>
</dependency>
 
<!-- Hibernate Validator -->
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-validator</artifactId>
	<version>5.1.2.Final</version>
</dependency>

In the Car class, add validation rules to some attributes using annotations:

@NotEmpty
private String name;
 
@Min(1000) @Max(5000000) // so we can add the Lamborghini Veneno
private BigDecimal price;

Perform the validation in the controller

In CarController, update the method processing the form submission:

@RequestMapping(value="/car/add", method=RequestMethod.POST)
public String carAddSubmit(@ModelAttribute("car") @Valid Car car, BindingResult result) {
	if(result.hasErrors()) {
		// show the form again, with the errors
		return "car/add";
	}
 
	// validation was successful
	carService.add(car);
	return "redirect:/car/list";
 
}
  • We added @Valid to the Car argument.
  • We added a BindingResult object as argument
  • We use the BindingResult object to check if the form had errors. If yes, we show the form again.

Add error tags in the JSP

In the JSP, for each form field, add a <form:errors> tag:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 
<html>
<body>
 
	<h1>Add a car</h1>
 
	<form:form method="POST" modelAttribute="car">
		<p>
			Name:
			<input type="text" name="name" />
			<form:errors path="name" cssclass="error"></form:errors>
		</p>
		<p>
			Price:
			<input type="text" name="price" />
			<form:errors path="price" cssclass="error"></form:errors>
		</p>
 
		<input type="submit" />
	</form:form>
 
</body>
</html>

If there's a validation error for a given field, <form:errors> will generate this HTML:

<span id="name.errors" cssclass="error">may not be empty</span>

Test wether it's working

Summary

We've added validation to an existing form by:

  • adding validation annotations in the domain class.
  • in the controller, re-displaying the form if there are any errors.
  • in the JSP, adding Spring tags to display error messages.

More validation annotations:

Create a custom annotation:

The source code is available on GitHub.

Next: you can find more in my book about Spring 4:

Previous: Display and process a form
Up: Spring MVC Fast Tutorial

Feedback

Thank you for this excellent series of tutorials on Spring MVC
Andrey
Aug 2, 2015
#1
In my application cssClass="error" doesn't change the format, where is definition of that css class?
Robert
Nov 26, 2015
#2
Robert: you have to define this CSS class yourself. Spring doesn't generate any CSS code.
Jerome Jaglale
Nov 26, 2015
#3
Thank you very much. This was exactly what I needed. I was about to give up on this spring thing. This is the first tutorial that I actually got to work all the way through. Not only that, the steps were incremental enough that I can actually figure out what the pieces do.

Now I just have to figure out how to add hibernate.
Alfreda
Jan 18, 2016
#4
Adding error message inside &lt;form:errors&gt; tags will be a nice example that we can customize the error message for each "input" element.

Big thank for your guide.
Tony Y P Zhang
Mar 26, 2016
#5
This is one of the best starters on Java Spring. Thank you!
Walt K
Jun 10, 2016
#6
My problem with the Spring books I've tried so far is them trying to teach more of the abstract stuff before just showing basic examples. The way this tutorial was done is brilliant in it's quick examples, along with some info about what does what.
THIS is how you should start a Spring tutorial. Show an easy example, then explain the under the hood stuff.
Walt K (again)
Jun 10, 2016
#7