Thursday , February 22 2018
Home / Spring / Spring Form Custom Validation Example

Spring Form Custom Validation Example

In this tutorial, I am going to show you how to validate Spring Form with Custom validations.

In the previous tutorial, we had a discussion about a simple and basic form validation of spring form. For this Spring Form Custom Validation I am going to take the basic form to some extent.

Technologies :

  • Spring Framework 3.1.1.RELEASE
  • Hibernate Validator 4.2.0.Final
  • Jstl 1.2
  • Java 8

Spring Form Custom Validation :

Project Structure :


Spring MVC Custom Form Validation Project-min

Create your own annotation for custom validation.

Recommended : Spring Boot Login From Validation Example

I am going to create CouponCode anotation which validates whether provided coupon code valid or not.

package com.spring.customannotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Constraint(validatedBy = CouponCodeValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface CouponCode {

	public String value() default "OTP";
	public String message() default "Coupon Code must starts with OTP";
	public Class<?>[] groups() default {};
	public Class<? extends Payload>[] payload() default{};

Applying Constraint validation using validation framework.

package com.spring.customannotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CouponCodeValidator implements ConstraintValidator<CouponCode, String> {

	private String couponCodePrefix;

	public void initialize(CouponCode couponCode) {
		couponCodePrefix = couponCode.value();

* You can write your own validation logic here. For now I am doing simple validation here like 
* checking whether coupon code startes with "OTP" or not.
	public boolean isValid(String couponCode, ConstraintValidatorContext constraintValidatorContext) {
		if (couponCode != null) {
			return couponCode.startsWith(couponCodePrefix);
		} else {
			return true;


Coupon code is valid iff, it startes with “OTP” otherwise it will throw default message like “Coupon Code must starts with OTP”.

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;

import com.spring.customannotation.CouponCode;

public class RegistrationBean {

	@Size(min = 1, message = "You can't leave this empty.")
	private String firstName;

	@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;
	private String couponCode;

	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) { = email;

	public String getCouponCode() {
		return couponCode;

	public void setCouponCode(String couponCode) {
		this.couponCode = couponCode;


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;

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";



<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@taglib uri="" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Validation</title>
.error {
color: red
<form:form action="processForm" modelAttribute="registration">

<div align="center">
<h2>Register Here</h2>
<td>First name</td>
<td><form:input type="text" path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
<td>Last name (*)</td>
<td><form:input type="text" path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
<td>Age </td>
<td><form:input type="text" path="age" /></td>
<td><form:errors path="age" cssClass="error" /></td>
<td>Email </td>
<td><form:input type="text" path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
<td>Coupon Code </td>
<td><form:input type="text" path="couponCode" /></td>
<td><form:errors path="couponCode" cssClass="error" /></td>
<td><input type="submit" value="Submit" /></td>

success.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<title>Registration Confirmation</title>
	Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us.

Test your Application :


Spring Custom Validation 2

Giving valid coupon code.

Spring Custom Validation 2 min


Spring Custom Validation 3-min

Happy Learning 🙂

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,


Spring Bean Autowire By Constructor Example

In this tutorial, we are going to learn about Spring bean autowire by constructor. In …

Leave a Reply

Your email address will not be published. Required fields are marked *