Here I am going show a simple Spring MVC Form Validation Example.
Technologies :
- Spring Framework 3.1.1.RELEASE
- Hibernate Validator 4.2.0.Final
- Jstl 1.2
- Java 8
Spring MVC Form Validation :
Here we are going to validate registration form with different fields like firstName, lastName, age, email by using simple spring validation framework.
Project Structure :
Spring MVC Form Validation Example :
Dependencies: pom.xml
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
RegistrationBean.java
package com.spring.controller;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class RegistrationBean {
@NotNull
@Size(min = 1, message = "You can't leave this empty.")
private String firstName;
@NotNull
@Size(min = 1, message = "You can't leave this empty.")
private String lastName;
@NotNull(message = "You can't leave this empty.")
@Min(value = 13, message = "You must be greater than or equal to 13")
@Max(value = 19, message = "You must be less than or equal to 19")
private Integer age;
@Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$", message = "Invalid email")
private String email;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@NotNull: It won’t allow the null values.
@Min(13): Won’t allow if the age is a min of 13
@Max(19): Won’t allow if the age is a max of 19
@Pattern: Applied given regex pattern on the specified field (our case it is email)
Registration Form : register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Validation</title>
<style>
.error {
color: red
}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="registration">
<div align="center">
<h2>Register Here</h2>
<table>
<tr>
<td>First name</td>
<td>
<form:input type="text" path="firstName" />
</td>
<td>
<form:errors path="firstName" cssClass="error" />
</td>
</tr>
<tr>
<td>Last name (*)</td>
<td>
<form:input type="text" path="lastName" />
</td>
<td>
<form:errors path="lastName" cssClass="error" />
</td>
</tr>
<tr>
<td>Age </td>
<td>
<form:input type="text" path="age" />
</td>
<td>
<form:errors path="age" cssClass="error" />
</td>
</tr>
<tr>
<td>Email </td>
<td>
<form:input type="text" path="email" />
</td>
<td>
<form:errors path="email" cssClass="error" />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
Registration Controller: RegistrationController.java
package com.spring.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
@Controller
public class RegistrationController {
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String showForm(Model model) {
model.addAttribute("registration", new RegistrationBean());
return "register";
}
@RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String processForm(@Valid @ModelAttribute("registration") RegistrationBean register,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "register";
} else {
return "success";
}
}
}
properties file :
typeMismatch.registration.age=Invalid Number
Success page: success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Registration Confirmation</title>
</head>
<body>
Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us.
</body>
</html>
Run the application :
http://localhost:8080/Spring-MVC-Form-Validation/register
Invalid Form Fields :
Leaving all form fields empty.
Invalid Age :
Using @Max and @Min validations on age attribute.
Invalid Age Format :
Giving invalid age (Not a number) validation
Success Form :
Success Page :
Happy Learning 🙂