Spring MVC Form Validation

spring-mvc-form-validation


aimIn our previous article we have seen how to submit a form. In this article we will show how to validate a form. The code whatever discussed here is annotation based form validation. Before going through this tutorial we advice you to read the below article

Form Submission Example in Spring MVC

1. Maven Dependency for Form Validation

We need extra two dependencies in pom.xml for the form validation. These are


<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>

2. Add below line in dispatcher-servlet.xml

<mvc:annotation-driven />

Remember without this tag validation is  not going to work.

3. The Model data

We are making firstName and lastName as mandatory by using @NotEmpty annotation


package com.proliferay.model;

import org.hibernate.validator.constraints.NotEmpty;

public class Customer {

@NotEmpty(message = "Please enter your first Name")
private String firstName;
@NotEmpty(message = "Please enter your last Name")
private String lastName;
private String address;
private String contact;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getContact() {
return contact;
}

public void setContact(String contact) {
this.contact = contact;
}

}

4. The customer form


<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Submission</title>
<style type="text/css">
.error {
color:#FF0000;
font-weight: bold;
}
</style>
</head>
<body>
<form:form method="POST" action="addCustomer" modelAttribute="customer">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
<td><form:errors cssClass="error" path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
<td><form:errors cssClass="error" path="lastName" /></td>
</tr>
<tr>
<td>Address:</td>
<td colspan="2"><form:input path="address" /></td>
</tr>
<tr>
<td>Contact:</td>
<td colspan="2"><form:input path="contact" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

Notice the modelAttribute and form:errors tag. The tag form:errors is used to display error if there are any errors after form submission.

5. The Controller

</p>
package com.proliferay.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proliferay.model.Customer;

@Controller

public class FormController {

@RequestMapping("/")
public ModelAndView showHomePage() {
return new ModelAndView("home", "customer", new Customer());
}

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addCustomer(@ModelAttribute("customer") @Valid Customer customer, BindingResult result) {

if (result.hasErrors()) {

return "home";

} else {

return "result";
}

}
}

Note 1: Using @Valid we are validating the captured model data submitted by the form.

Note 2: BindingResult result holds the error information in the form.

Note 3: If there are errors then we are going back again to the submitted form otherwise the result page

6. The result page

<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Customer Information</h2>
<table>
<tr>
<td>First Name:</td>
<td>${customer.firstName}</td>
</tr>
<tr>
<td>Last Name:</td>
<td>${customer.lastName}</td>
</tr>
<tr>
<td>Address:</td>
<td>${customer.address}</td>
</tr>
<tr>
<td>Contact:</td>
<td>${customer.contact}</td>
</tr>
<tr>
<td colspan="2"><a href="${pageContext.request.contextPath}">Back</a></td>
</tr>
</table>
</body>
</html>

7. Keep the error message in properties file
We can keep the error message in properties file. To use properties file for this purpose add the below in dispatcher-servlet.xml

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>

We can create our properties file in the resource folder. The properties file messages.properties may look like


NotEmpty.customer.firstName=Please enter your first name.

Where

NoteEmpty is the error type

customer is the command object. See the code of the form

firstName is the property of the Customer class

Note : If there are no properties file for the error messages then error message will be picked from the model class. For example below will be picked from Customer.java

@NotEmpty(message = “Please enter your first Name”)
    private String firstName;

Summery:

We have only shown @NotEmpty for two fields. However there are many error types. You can explore those. We can also write our own custom Validator.

Download Source Code

 

About The Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
%d