Open In App
Related Articles

Spring – MVC Custom Validation

Like Article
Save Article
Report issue

Prerequisites: Spring MVC, Spring MVC Validation

It is necessary to validate user input in any web application to ensure the processing of valid data. The Spring MVC framework supports the use of validation API. The validation API puts constraints on the user input using annotations and can validate both client-side and server-side. It provides standard predefined validators like @Min, @Max, @Size, @Pattern, and @NotNull. In case we have to process a more specific input spring MVC also provides the concept of user-defined validators with custom validation logic. In this article, we’ll create a custom validator to validate the address of a student in a student portal.

Steps to create a Student form with custom validation

Firstly, we need to create a maven webapp project, in this tutorial we’ll use Eclipse IDE. Now, choose to create maven while creating a new project and add a maven webapp archetype. Enter the group id and the artifact id for your project and click finish.

A maven web project would be created with a pom.xml configuration file. The project structure would look something like this:

Now, let’s configure the pom.xml configuration file to add dependencies. Maven will get and manage all the dependencies defined in this file. You will need to add all these dependencies to be able to use the methods. The hibernate-validator dependency allows to express and validate application constraints.


<?xml version="1.0" encoding="UTF-8"?>
  <name>SpringMvcStudentValidation Maven Webapp</name>
  <!-- FIXME change it to the project's website -->


The web.xml file in the “webapp/WEB-INF/web.xml” defines mapping with different URLs and servlets to handle requests for those URLs. In this, we have defined the servlet XML file to be named as gfg. The URL-pattern is set as “/”, which means any request with “/” will be sent to the dispatcher servlet to be handled.


    <display-name>To do List</display-name>



The gfg-servlet.xml file is located in  “/src/main/webapp/WEB-INF/gfg.servlet.xml”. This file is named after the servlet-name we have mentioned in the web.xml file, it handles all HTTP requests for the web applications. The annotation-driven enable the spring annotation classes. The bean configuration helps in identifying and scanning the jsp located in the views folder. The component scan locates and allocated beans according to the defined annotation. It’s a pretty simple file to handle incoming HTTP calls.



    <context:component-scan base-package="com.gfg" />
        <property name="prefix">
        <property name="suffix">
    <mvc:annotation-driven />



Now, we’ll create a student class in the com.gfg.model package, for our student portal we’ll show four attributes firstName, lastName, rollNo, and address. The first two fields have @Size validation annotation as a constrain of min size as one, so they can’t be empty. For roll number, we have used @Min which is also a predefined validator. Now, for address, we have used @Address which is a custom validator that we are going to define and configure.



package com.gfg.model;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.gfg.validationconfig.Address;
public class Student {
    @Size(min = 1, message = "Student first name can't be empty")
    private String firstName;
    @Size(min = 1, message = "Student last name can't be empty")
    private String lastName;
    @Min(value = 1000, message = "Roll number must be a four digit number")
    private int rollNo;
     // custom validation
    private String address;
    public Student(@NotNull String firstName, @NotNull String lastName,
        @Min(value = 1000, message = "Roll number must be a four digit number")
        int rollNo,
        @Size(min = 20, message = "Address must contains atleast 20 letters") @Size(max = 40, message = "Address must contains atleast 20 letters")
        String address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.rollNo = rollNo;
        this.address = address;
    public Student() {
    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 int getRollNo() {
        return rollNo;
    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    public String getAddress() {
        return this.address;
    public void setAddress(String address) {
        this.address = address;


The Controller class handles the incoming requests by redirecting them to the appropriate view page, any URL must be defined in the controller class in order to send a request. In this project, we have defined a StudentController class in com.gfg.controller package. In this class we have two methods for two request, the first one simply redirects to the login portal and simply add a new student object to match the inputs into the form using the model’s addAttribute. The second method redirects to the welcome page, but before that, it checks for any validation errors using the BindingResult. If there exists an error it redirects to the portal else to the welcome page.


package com.gfg.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 com.gfg.model.Student;
public class StudentController { 
    public String showForm(Model theModel) { 
        theModel.addAttribute("student", new Student());
        return "portal";
    public String processForm(@Valid @ModelAttribute("student") Student student, BindingResult result) {                
        if (result.hasErrors()) {
            return "portal";
            return "welcome";


The AddressValidator class in the com.gfg.validationcongfig package defines the constrain for which the object needs to be checked, this class implements the ConstraintValidator which defines the logic to validate a given constrain. We override a method class isValid from the ConstrainValidator interface, where we define our validation logic.


package com.gfg.validationconfig;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class AddressValidator implements ConstraintValidator<Address, String> {
    public boolean isValid(String s, ConstraintValidatorContext cvc) { 
        s = s.toLowerCase();
        boolean result = s.contains("india");
        return result; 


Now, we create an Address annotation using the @interface, This class must have three overridden in order for the validation logic to work. The first method defines the error message to be shown, the second method represents a group of constraints, the third method represents additional information about the annotation. The @Constraint, @Target, and @Retention annotation define the validation logic, the element to be passed, and additional information.


package com.gfg.validationconfig;
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 = AddressValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD } ) 
public @interface Address {
    public String message() default "You address must contains india";
        public Class<?>[] groups() default {}; 
        public Class<? extends Payload>[] payload() default {}; 


The portal.jsp page the “/webapp/WEB-INF/views/portal.jsp” defines the student login portal. We have used the form configuration to format our form. This is a pretty simple form that defines four fields.


<%@ taglib prefix="form" uri="" %> 
        .error {color:red} 
    <h1>Student Portal</h1>
    <form:form action="welcome" modelAttribute="student"
        <label>First name:</label>
         <form:input path="firstName" />
         <form:errors path="firstName" cssClass="error" /><br><br
         <label>Last name:</label>
         <form:input path="lastName" /> 
        <form:errors path="lastName" cssClass="error" /><br><br>   
         <label>Roll No:</label>
          <form:input path="rollNo" />
         <form:errors path="rollNo" cssClass="error" /><br><br>   
         <form:textarea path="address" /> 
        <form:errors path="address" cssClass="error" /><br><br>   
        <input type="submit" value="Submit" /> 


The welcome.jsp page in the “/webapp/WEB-INF/views/welcome.jsp” is the view page that is shown after successful login.


<%-- <%@ taglib prefix="c" uri="" %>
<!DOCTYPE html> 
            <h2>Welcome ${student.firstName} ${student.lastName} to Student portal<br><br
            Your Roll Number is ${student.rollNo} and you live in india.</h2>


Now, that our Spring MVC project has been completed with all the configuration files and classes. The Structure of your project should look like this:

Project Structure

Project Structure


It’s time to run your web application on the tomcat server. I am assuming you know how to run a tomcat server. After successfully running the tomcat server enter http://localhost:8080/SpringMvcStudentValidation/welcome in your favorite browser.


So, we have created a Spring MVC project with our own validation and used it in a student portal form.

Last Updated : 10 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Similar Reads