Spring Form Validation Example


In today’s discussion we will dive into form validation in spring, by the end of this tutorial we will be able to email validation, phone number validation and other spring form validation techniques.

 To implement spring form validation we need to create a separate Java class, all validation part will be covered in that file.

1) Simple Java Class to specify validation conditions and messages.

FormValidation.java

Everything related to form validation in spring goes here. Create a simple java class and make it implement a pre defined interface so called 'Validator'. There are two methods in validator interface override them in your own class and write validation code in validate() method.
package com.developerfirm.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.developerfirm.domain.Student;

public class FormValidation implements Validator {

private Pattern pattern;
private Matcher matcher;

private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String ID_PATTERN = "[0-9]+";
String STRING_PATTERN = "[a-zA-Z]+";
String MOBILE_PATTERN = "[0-9]{10}";

@Override
public boolean supports(Class arg0) {
// TODO Auto-generated method stub
return false;
}

@Override
public void validate(Object target, Errors errors) {

Student student = (Student) target;

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "required.id",
"Id is required.");

// input string conatains numeric values only
if (student.getId() != null) {
pattern = Pattern.compile(ID_PATTERN);
matcher = pattern.matcher(student.getId().toString());
if (!matcher.matches()) {
errors.rejectValue("id", "id.incorrect",
"Enter a numeric value");
}

// input string can not exceed that a limit
if (student.getId().toString().length() > 5) {
errors.rejectValue("id", "id.exceed",
"Id should not contain more than 5 digits");
}
}

ValidationUtils.rejectIfEmpty(errors, "name", "required.name",
"Name is required.");

// input string conatains characters only
if (!(student.getName() != null && student.getName().isEmpty())) {
pattern = Pattern.compile(STRING_PATTERN);
matcher = pattern.matcher(student.getName());
if (!matcher.matches()) {
errors.rejectValue("name", "name.containNonChar",
"Enter a valid name");
}
}

//radio buttons validation
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender",
"required.gender", "Select your gender");

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email",
"required.email", "Email is required.");

// email validation in spring
if (!(student.getEmail() != null && student.getEmail().isEmpty())) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(student.getEmail());
if (!matcher.matches()) {
errors.rejectValue("email", "email.incorrect",
"Enter a correct email");
}
}

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone",
"required.phone", "Phone is required.");

// phone number validation
if (!(student.getPhone() != null && student.getPhone().isEmpty())) {
pattern = Pattern.compile(MOBILE_PATTERN);
matcher = pattern.matcher(student.getPhone());
if (!matcher.matches()) {
errors.rejectValue("phone", "phone.incorrect",
"Enter a correct phone number");
}
}

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
"required.password", "Password is required.");

// password matching validation
if (!student.getPassword().equals(student.getConfirmPassword())) {
errors.rejectValue("confirmPassword", "password.mismatch",
"Password does not match");
}

// drop down list validation
if (student.getCity().equals("select")) {
errors.rejectValue("city", "city.select", "select a city");
}

// text area validation
ValidationUtils.rejectIfEmpty(errors, "overview", "required.overview",
"Overview is required.");

// checkbox validation
if (student.getInterest().length <= 0) {
errors.rejectValue("interest", "noselect.interest",
"Select atleast one interest");
}
}
}
Now the next step is to add an entry of this Validation code in our controller. Here is an example of how to make changes in controller:

2) Changes in controller

FormController.java

The next step is to tell the controller about the validatuion class so that the form data goes to validation process before processed. See the code below to get it clear:
package com.developerfirm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.developerfirm.domain.Student;
import com.developerfirm.validator.FormValidation;

@Controller
public class FormController {

@RequestMapping("/showForm")
public String getForm(ModelMap model) {

Student student = new Student();
model.addAttribute("student", student);

getList(model);
return "Register";
}

@RequestMapping("/submit")
public String saveForm(Student student, BindingResult result, ModelMap model) {
FormValidation formValidation = new FormValidation();

formValidation.validate(student, result);

if (result.hasErrors()) {
getList(model);
return "Register";
}

student = (Student) result.getModel().get("student");
System.out.println(student.getId());
return "Details";
}

public void getList(ModelMap model) {
HashMap<String, String> cityList = new HashMap<String, String>();

cityList.put("paris", "Paris");
cityList.put("new york", "New York");
cityList.put("tokyo", "Tokyo");
cityList.put("roma", "Roma");
model.addAttribute("cityList", cityList);

ArrayList<String> interestList = new ArrayList<String>();
interestList.add("reading");
interestList.add("cricket");
interestList.add("movies");
model.addAttribute("interestList", interestList);
}
}
Now the very last step is to make our spring form aware of validation stuff and set the error message location. See the example Jsp file below:

3) Changes in Jsp containing Spring Form

Register.jsp

The very last and final step is to show error messages on Jsp. Error messages can be shown usnig tags and passing appropriate field name in it. See the example below :

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Being Java Guys | Registration Form</title>
</head>
<body>
<center>
<div style="color: teal; font-size: 30px">Being Java Guys |
Registration Form</div>
<form:form action="submit.html" commandName="student" method="post">
<table>
<tr>
<td>Id:</td>
<td><form:input path="id" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="id" />
</td>
</tr>
<tr>
<td>Name:</td>
<td><form:input path="name" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="name" />
</td>
</tr>
<tr>
<td>Gender:</td>
<td><form:radiobutton path="gender" value="Male" /> Male
<form:radiobutton path="gender" value="Female" /> Female</td>
<td style="color: red; font-style: italic;"><form:errors
path="gender" />
</td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="email" />
</td>
</tr>
<tr>
<td>Phone:</td>
<td><form:input path="phone" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="phone" />
</td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="password" />
</td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><form:password path="confirmPassword" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="confirmPassword" />
</td>
</tr>
<tr>
<td>City:</td>
<td><form:select path="city">
<form:option value="select">---select---</form:option>
<form:options items="${cityList}" />
</form:select>
</td>
<td style="color: red; font-style: italic;"><form:errors
path="city" />
</td>
</tr>
<tr>
<td>Overview:</td>
<td><form:textarea path="overview" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="overview" />
</td>
</tr>
<tr>
<td>Interest:</td>
<td><form:checkboxes items="${interestList}" path="interest" />
</td>
<td style="color: red; font-style: italic;"><form:errors
path="interest" />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" />
</td>
</tr>
</table>
</form:form>
</center>
</body>
</html>

This is all about implementing form validation in a spring MVC application. A complete working example can be downloaded from Here. 

In today’s discussion we came across basic spring form tags and server side validation in spring forms. In upcoming tutorials we will see more about spring and other Java technologies.