Spring - MVC Regular Expression Validation

Last Updated : 4 Jun, 2026

Spring MVC Regular Expression Validation is used to validate user input against a specific pattern using regular expressions. It is commonly implemented with the @Pattern annotation provided by Hibernate Validator, ensuring that data entered by users follows the required format before processing.

  • Validates input formats such as email addresses, phone numbers, usernames, and passwords.
  • Uses the @Pattern annotation to define custom validation rules with regular expressions.
  • Helps improve data integrity and prevents invalid data from being submitted to the application.

Syntax

@Pattern(regex = "", flags = {}, message = "")
private String someDataMember;

  • regex : Specifies the regular expression pattern that the field value must match.
  • flags : Optional matching flags (such as case-insensitive matching) used while evaluating the regular expression.
  • message : Custom error message displayed when the validation fails.

Steps to Implement Regular Expression Validation in Spring MVC

Follow these steps to create a Spring MVC application that validates username and password using the @Pattern annotation.

Step 1: Create Spring Boot Maven Project

  • Open Eclipse IDE and create a new Spring Boot Maven Project.
  • This project will contain all the files required for building the Spring MVC Regular Expression Validation application. Maven automatically manages the project dependencies.

Step 2: Add Required Dependencies

These dependencies provide support for Spring MVC, Thymeleaf templates, Bean Validation, and Lombok.

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Step 3: Create Project Structure

This structure separates the model, controller, and view files, making the application easier to maintain.

Project structure
Project structure for guest login application

Step 4: Create User Model Class

The User class stores login information and applies regular expression validation rules on username and password fields.

User class (Data model): 

Java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
class User {

    @Pattern(regexp = "^[a-zA-Z0-9]{6,12}$",
            message = "username must be of 6 to 12 length with no special characters")
    private String username;

    @Pattern(regexp = "^((?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])){4,12}$",
            message = "password must contain atleast 1 uppercase, 1 lowercase, 1 special character and 1 digit ")
    private String password;
}

Step 5: Complete Controller Class

The complete controller contains both GET and POST request handlers.

Java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;

@Controller
public class LoginController {

    @GetMapping("/")
    public String getForm(User user) {
        return "login";
    }

    @PostMapping("/")
    public String login(@Valid User user, Errors errors, Model model) {
        if (errors.hasErrors()) {
            return "login";
        } else {
            model.addAttribute("message", "Guest login successful ...");
            return "login";
        }
    }
}

Note : 

  • The @Controller annotation indicates that a particular class serves the role of a controller.
  • @GetMapping is used to handle GET type of request method.
  • @PostMapping is used to handle POST type of request method.

Step 6: Create Thymeleaf Login Page

This page contains the login form and displays validation errors generated by Spring MVC.

HTML
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
    <title>Guest Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
    <h1 th:text="${message}" style="text-align: center; padding-top: 40px"></h1>

    <div class="container" style="padding-top: 50px ">
        <h2>Guest login</h2>
        <form action="/" th:action="@{/}" th:object="${person}" method="post" style="padding-top: 30px">
            <div class="form-group">
                <label for="username">Username:</label>
                <input type="text" class="form-control" id="username" placeholder="Enter username" name="username" th:field="*{username}"> <br />
                <p th:if="${#fields.hasErrors('username')}" th:errors="*{username}" class="alert alert-danger"></p>

            </div>
    
            <div class="form-group">
                <label for="password">Password:</label>
                <input type="text" class="form-control" id="password" placeholder="Enter password" name="password" th:field="*{password}"> <br />
                <p th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="alert alert-danger"></p>

            </div>
    
            <div class="form-group form-check">
                <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="remember">
                    Remember me
                </label>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>

</body>
</html>

Step 7: Run the Application

  • Right-click SpringMvcValidationApplication.java.
  • Select Run As -> Java Application if the Spring Boot option is not available.

Open a web browser and access the application:

http://localhost:8080/yourFormUrl

Output:

Output

Let's try to validate it with some invalid input data. Example:

  • Username: anu0-0
  • Password: QWqw123

Since the username doesn't allow special characters and the password requires a special character, error messages will be passed to the login page and then rendered showing that the input data doesn't match the given regex format.

Output
Invalid input data

Let's try to validate it with some valid input data. Example: 

  • Username: anu000
  • Password: QWqw@123

OutputExplanation: When the form is submitted, Spring MVC binds the request data to the User object and validates it using the @Pattern annotations. If any validation rule is violated, the corresponding error message is displayed; otherwise, the success message is shown on the login page.

Comment