Spring MVC Form Validation Using Annotation

Spring MVC Form Validation Using Annotation

Spring MVC @valid or Spring MVC form validation using annotation
Below example will show you how to do Spring MVC application form validation using annotation.

Below are needed

Please follow below steps:

  • Create dynamic web project in eclipse name: DynamicRowAddSpring (Please use this link if you are not familiar how to create dynamic project in eclipse: Create Dynamic Web Project Eclipse)
  • Create bean class and annotate with hibernate validator annotation. For this you will have to add hibernate annotation validation jar in your project. Create package com.javahorn.beans inside src folder and create classes inside it with same name from below:
package com.javahorn.beans;

import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.NotEmpty;

public class Users {

	private String name;
	// below pattern will match data in MM/DD/YYYY format
	@Pattern(regexp = "((?:0[1-9])|(?:1[0-2]))\\/((?:0[0-9])|(?:[1-2][0-9])|(?:3[0-1]))\\/(\\d{4})")
	private String dob;
	private String email;
	private String phone;

	public Users(String name, String dob, String email, String phone,
			String address, Long pincode, String country) {
		this.name = name;
		this.dob = dob;
		this.email = email;
		this.phone = phone;

	public Users() {

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public String getDob() {
		return dob;

	public void setDob(String dob) {
		this.dob = dob;

	public String getEmail() {
		return email;

	public void setEmail(String email) {
		this.email = email;

	public String getPhone() {
		return phone;

	public void setPhone(String phone) {
		this.phone = phone;



  • Please have a look above code I have created field validation and their annotation. Below is again screen shot:

Spring MVC Form Validation Using Annotation


  • Create controller name TestController.java and copy paste below code. To do form validation to work, please annotate the “JSR annotated model object” via @Valid.
package com.javahorn.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.javahorn.beans.Users;

public class TestController {

	@RequestMapping(value = "/helloWorld.web", method = RequestMethod.GET)
	public ModelAndView printWelcome(@ModelAttribute("user") Users user) {

		ModelAndView mav = new ModelAndView("SubmitForm");
		mav.addObject("message", "Hello World!!!");
		return mav;


	@RequestMapping(value = "/submitForm.web", method = RequestMethod.POST)
	public ModelAndView submitForm(@Valid @ModelAttribute("user") Users user,BindingResult bindingResult) {

		Users users=new Users();
		ModelAndView mav = new ModelAndView("SubmitForm");
		mav.addObject("users", users);
		return mav;




  • Create dispatcher-servlet.xml inside WEB-INF folder and copy paste below content. Please note: To validate form using annotation you will have to add: tag and to read error message from properties files you will to add ResourceBundleMessageSource bean. Please copy paste below xml file and paste to your dispatcher-servlet.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

	<context:component-scan base-package="com.javahorn.controller" />
	<context:component-scan base-package="com.javahorn.beans" />
	<mvc:annotation-driven /> 

		<property name="prefix">
		<property name="suffix">

	<!-- bind your messages.properties -->
	<bean class="org.springframework.context.support.ResourceBundleMessageSource"
		<property name="basename" value="messages" />



  • Error message configuration: You already added bean class in dispatcher-servlet.xml file now create messages.properties file inside src folder and copy paste below content in it.
NotEmpty.user.name = Name is required!
NotEmpty.user.dob = DOB is required!
Pattern.user.dob = DOB format not matched (MM/DD/YYYY)
NotEmpty.user.email = Email is required!
NotEmpty.user.phone = Phone is required!


  • Create folder name jsp inside WEB-INF folder and create jsp file name SubmitForm.jsp. Copy paste below jsp content in it
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style type="text/css">
.error{color: #ff0000;font-size: 14px;height: 3px;font-weight: bold;}

<form:form commandName="user" action="submitForm.web" method="post">     

                <legend>User details</legend>
                        <label for=name>Name</label>
                        <form:input path="name"  type="text" placeholder="First and last name" />
                        <form:errors path="name" class="error"/>
                        <label for=name>Date</label>                        
                    <form:input path="dob" type="date" required="true" />
                    <form:errors path="dob" class="error"/>
                        <label for=email>Email</label>
                        <form:input path="email" type="text"/>
                        <form:errors path="email" class="error"/>
                        <label for=phone>Phone</label>
                        <form:input path="phone" type="text"/>
                        <form:errors path="phone" class="error"/>
                <button type=submit>Save User Details!</button> 



  • That’s it. Finally your project structure should look like below:

Spring MVC Form Validation Using Annotation


  • Now right click project –> Click Run As –> Run on Server as below:

Spring MVC Form Validation Using Annotation


  • You will see below. URL: http://localhost:8080/DynamicRowAddSpring/

Spring MVC Form Validation Using Annotation


  • Once you Click Save User Details button you will see below validation error message.

Spring MVC Form Validation Using Annotation


  • That’s it we are done with Spring MVC Form Validation Using Annotation .

Leave a Reply

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

I am not Robot *