Spring MVC - Number Validation

Last Updated : 3 Jun, 2026

Spring MVC Number Validation is used to validate user input before processing it in a web application. Spring provides built-in Bean Validation support through standard validation annotations, allowing developers to enforce rules such as numeric ranges, required fields, date validation, and format checking with minimal code.

  • Uses Bean Validation annotations such as @Digits, @Min, @Max, and @NotEmpty to validate form data.
  • Automatically displays validation error messages and prevents invalid data from being processed.
  • Integrates seamlessly with Spring MVC using the @Valid annotation and BindingResult.

Validation - Api

The validation-api dependency provides the standard Bean Validation specification in Java. It contains built-in validation annotations such as @NotNull, @Min, @Max, @Digits, @Pattern, and @Size, which can be applied to bean properties to validate user input.

Annotation TypeDescription
@AssertFalseValidates that the annotated boolean value is false.
@AssertTrueValidates that the annotated boolean value is true.
@DigitsValidates that a numeric value contains a specified number of integer and fractional digits.
@NotNullEnsures that the annotated element is not null.
@MinValidates that a numeric value is greater than or equal to the specified minimum value.
@PastValidates that the annotated date or time value is in the past.
@PatternValidates that a string matches the specified regular expression.
@SizeValidates that the size or length of a string, collection, map, or array is within the specified range.
@MaxValidates that a numeric value is less than or equal to the specified maximum value.
@FutureValidates that the annotated date or time value is in the future.

To use these annotations, we need to add the below dependency in the 'pom.xml' file.

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>

hibernate-validator

The hibernate-validator dependency is the reference implementation of the Bean Validation API. It provides additional validation annotations such as @Email, @NotEmpty, @Range, and @CreditCardNumber, and is responsible for executing the validation rules defined on bean properties.

Annotation TypeDescription
@CreditCardNumberValidates that the annotated value is a valid credit card number using the Luhn algorithm.
@EmailValidates that the annotated string is a well-formed email address.
@LengthValidates that the length of a string is within the specified minimum and maximum limits.
@NotEmptyEnsures that a string, collection, map, or array is neither null nor empty.
@RangeValidates that a numeric value falls within the specified minimum and maximum range.
@URLValidates that the annotated string is a valid URL.
@Mod11CheckValidates a value using the Modulo 11 checksum algorithm.

To use these annotations, we need to add the below dependency in the 'pom.xml' file.

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>

Steps to implements Number Validation in Spring MVC Application

Follow these below steps to create an application with Number validation in Spring MVC.

Step 1: Create a Maven Project

  • Open Eclipse IDE.
  • Click File -> New -> Maven Project.
  • Select Create a simple project (skip archetype selection).
  • Click Next.
Project Structure
Project Structure

Step 2: Configure Maven Project

Enter the project details:

  • Group Id: com.example
  • Artifact Id: validation
  • Packaging: war

Click Finish.

Step 3: Add Required Dependencies

Open pom.xml and add the following dependencies:

XML
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.10</version>
</dependency>

Step 4: Create the Bean Class(Info.java)

This class acts as the model object and stores user-entered data. Validation annotations are applied to each field to define validation rules.

Java
package com.geeksforgeeks.app;

import java.util.Date;

import javax.validation.constraints.Digits;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.CreditCardNumber;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

public class Info {
    
    @NotEmpty(message = "Enter your name.")
    private String name;
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    @Past(message = "Enter valid date.")
    private Date birthDate;
    @Pattern(regexp = "\\d{10}",message = "Phone number must contain exactly 10 digits.")
    private String phNum;
    @Email(message="Enter valid Email Id.")
    private String email;
    @CreditCardNumber(message="Enter valid card number.")
    private String card;
    
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getCard() {
        return card;
    }
    public void setCard(String card) {
        this.card = card;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthDate() {
        return birthDate;
    }
    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }
    public String getPhNum() {
        return phNum;
    }
    public void setPhNum(String phNum) {
        this.phNum = phNum;
    }
    
}

Step 5: Create the Controller Class(InfoController.java)

The controller displays the form page, validates submitted data using @Valid, and redirects users based on the validation result.

Java
package com.geeksforgeeks.app;

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 InfoController {
    
    @RequestMapping(value = "/")
    public String viewPage(Model model) {

        Info info = new Info();
        model.addAttribute("info", info);
        return "info";
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("info") Info info, BindingResult result) {
        if (result.hasErrors()) {
            return "info";
        }
        else {
            return "summary";
        }
    }

}

Step 6: Create the Input Form Page(info.jsp)

Spring Form tags are used to bind form fields with the Info object and display validation errors next to the corresponding fields.

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>

    <h2>Welcome to GeeksforGeeks!!</h2>
    <h3>Please fill in the form</h3>
    <form:form action="submit" method="post" modelAttribute="info">
        <table>
            <tr>
                <td><form:label path="name">Full Name: </form:label></td>
                <td><form:input path="name" />
                <form:errors path="name" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:label path="birthDate">Date of Birth: </form:label></td>
                <td><form:input path="birthDate" />
                <form:errors path="birthDate" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:label path="phNum">Phone Number: </form:label></td>
                <td><form:input path="phNum" />
                <form:errors path="phNum" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:label path="email">Email Id: </form:label></td>
                <td><form:input path="email" />
                <form:errors path="email" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:label path="card">Card Number: </form:label></td>
                <td><form:input path="card" />
                <form:errors path="card" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:button>Submit</form:button></td>
            </tr>
        </table>
    </form:form>

</body>
</html>

Step 7: Create the Summary Page(summary.jsp)

This page is shown only when all validation rules are satisfied and the form submission is successful.

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Summary page</title>
</head>
<body>

    <h3>Details submitted!</h3>

    <table>
        <tr>
            <td>Name:</td>
            <td>${info.name}</td>
        </tr>
        <tr>
            <td>Date of Birth:</td>
            <td>${info.birthDate}</td>
        </tr>
        <tr>
            <td>Phone Number:</td>
            <td>${info.phNum}</td>
        </tr>
        <tr>
            <td>Email:</td>
            <td>${info.email}</td>
        </tr>
        <tr>
            <td>Card Number:</td>
            <td>${info.card}</td>
        </tr>
    </table>

</body>
</html>

Step 8: Run Your Application

  • Right-click project.
  • Select Run As -> Run on Server.
  • Choose Apache Tomcat Server.
  • Click Finish.

Open the browser and access:

http://localhost:8080/app

Output:

Welcome Form
Welcome Form

If we enter the invalid inputs, it will display the same page with the error information like below,

Invalid inputs
Invalid inputs

Now, enter the valid inputs to process the form successfully.

Valid Inputs
Valid Inputs

Click on submit to get the output.

Output
Output

Explanation : When the user submits the form, Spring MVC binds the entered data to the Info object and validates it using the Bean Validation annotations applied to the class fields. If any validation rule is violated, the corresponding error messages are displayed on the same form page. Otherwise, the request is processed successfully and the user is redirected to the summary page displaying the submitted details.

Comment