Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring - MVC Regular Expression Validation
Next article icon

Spring - MVC Regular Expression Validation

Last Updated : 21 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation.

Syntax:

@Pattern(regex="", flag="", message="") private String someDataMember;

Note that the flag and message attributes are optional. Let's build a simple web application for a better understanding of how to use Regex validation in Spring MVC. In this application, we will build a guest login page.

Example

Project structure: 

Project structure
Project structure for guest login application

Regex Usage: 

The @Pattern annotation makes sure that the value passed to the data member follows the provided regular expressions. The attribute regexp takes the regular expression to be matched.

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

In the above code snippet, the regular expression says that a username can contain any lowercase characters, any uppercase characters, or any digit only. Also, the username can only be of 6 to 12 lengths (inclusive).

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

In the above code snippet, the regular expression says that the password must contain at least 1 lowercase letter, 1 uppercase letter, 1 special character, and 1 digit and it must be of size 4 to 12 inclusive. 

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

The User class acts as a data model for our application. Here we have used Lombok to reduce boilerplate code. The User class consists of only 2 fields required for our guest login page.

APIs: Our application consists of the following APIs.

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

The above code snippet demonstrates the GET API which is used here to render the login.html page residing in our resources/templates files. The endpoint for the GET API is "/".

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

The above code snippet demonstrates the POST API which is used to take login form input and passes the errors (if any) of the regex validation to the login page which then renders it.

Complete Controller Class: 

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.

Login page (Html + Thymleaf): 

HTML
<!DOCTYPE html> <html lang="en" xmlns:th="http://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> 

The above code represents our login page. Here we have used thymleaf instead of JSP which is a templating engine that is certainly a better way of creating templates.

Dependency:

Add the below dependencies in the pom.xml file.

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.springframework.boot</groupId>             <artifactId>spring-boot-devtools</artifactId>             <scope>runtime</scope>             <optional>true</optional>         </dependency>         <dependency>             <groupId>org.projectlombok</groupId>             <artifactId>lombok</artifactId>             <optional>true</optional>         </dependency>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-test</artifactId>             <scope>test</scope>         </dependency> 

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

Output


Next Article
Spring - MVC Regular Expression Validation

A

anuanu0_0
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Spring MVC - Multiple Resolver Mapping
    Spring MVC Framework provides the feature of View Resolver through which you can map a view to its respective view and render the model in your browser. The View Resolver eliminates the use of view technologies like Velocity and JSP. There are many view resolvers available in spring-like InternalRes
    4 min read
    How to Extract TV Show Details via REST API and Spring MVC?
    REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applicat
    9 min read
    Spring MVC File Upload
    Spring MVC provides a robust mechanism for handling file uploads in web applications. Using Spring MVC file upload, developers can easily integrate multipart file handling with the CommonsMultipartResolver. This article covers how to upload files in Spring MVC, configure MultipartResolver, and manag
    6 min read
    Spring MVC - Tiles
    Spring provides functionality for integrating with the Apache Tiles framework. With the help of spring tiles support, we can easily manage the layout of the Spring MVC application. Benefits of Spring MVC's Tiles support: The following are some of the primary benefits of Spring MVC Tiles 3 Integratio
    4 min read
    Spring MVC - Text Box
    To begin, make sure you have a working Eclipse IDE installed and follow the steps below to create a Spring Web Framework-based Dynamic Form-based Web Application. Steps to create TextBox in Spring MVC: Create a SpringMVCTextField project in the com.geeksforgeeks package.Under the com.geeksforgeeks p
    3 min read
    Spring MVC - Multiple Controller
    We may construct numerous controllers at once in Spring MVC. Each controller class must be annotated with the @Controller annotation. A Spring MVC example with numerous controllers can be found here. The procedure is as follows: In the case of Maven, load the spring jar files or add dependencies.Mak
    2 min read
    Spring MVC - Model Interface
    The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
    7 min read
    Spring MVC - Number Validation
    The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
    9 min read
    Spring - MVC Form Checkbox
    In this article, we will learn about the Spring MVC Checkbox and Checkboxes tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create checkboxes using form:checkbox and form:checkboxes tags. 'spring-form.tld' tag library In Spring Framework, we can use Java Server Pages
    6 min read
    Spring - MVC Form Radio Button
    Here, we will learn about the Spring MVC radiobutton and radiobuttons tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create radiobuttons using form:radiobutton and form:radiobuttons tags. 'spring-form.tld' tag libraryIn Spring Framework, we can use Java Server Pages
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences