Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
Regular expression validation in Spring MVC can be achieved using the @Pattern
annotation provided by the Java Bean Validation (JSR 303) API. This annotation allows you to specify a regex pattern that the annotated field's value must match.
Let's walk through an example where we'll validate a form field using a regular expression in a Spring MVC application:
First, ensure you have the required dependencies for Spring MVC and Bean Validation:
<!-- Spring Web MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.x.x.RELEASE</version> </dependency> <!-- Hibernate Validator (JSR 303 implementation) --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.x.x.Final</version> </dependency> <!-- Validation API --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.x.x.Final</version> </dependency>
Suppose you have a user registration form and you want to ensure that the username field contains only alphanumeric characters:
public class UserRegistrationForm { @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Username must be alphanumeric") private String username; // Other fields, getters, setters, etc. }
In the above example, the regex ^[a-zA-Z0-9]+$
ensures the username is made up of only alphanumeric characters.
When the form is submitted, you can check for validation errors:
@Controller @RequestMapping("/register") public class RegistrationController { @PostMapping public String register(@Valid UserRegistrationForm form, BindingResult result) { if (result.hasErrors()) { return "registrationForm"; // return back to the form page if there are errors } // Proceed with registration logic return "success"; } }
In your JSP or Thymeleaf view, you can display validation errors:
JSP example:
<form:form modelAttribute="userRegistrationForm" action="register" method="post"> <form:input path="username" /> <form:errors path="username" cssClass="error-message" /> <!-- other form fields --> <input type="submit" value="Register" /> </form:form>
With this setup, if a user enters a username that doesn't match the specified regular expression, they will receive the error message: "Username must be alphanumeric".
This is a simple example, but you can craft more complex regular expressions to suit your validation needs. Always remember to test your regular expressions thoroughly to ensure they match the desired patterns and exclude undesired ones.
Spring MVC Regular Expression Validation Example:
Description: This is a basic example demonstrating regular expression validation in a Spring MVC application.
Code Snippet: (Model)
public class User { @Pattern(regexp = "^[a-zA-Z0-9]{5,10}$", message = "Username must be alphanumeric and between 5 to 10 characters") private String username; // Getter and Setter }
(Controller)
@Controller public class UserController { @PostMapping("/register") public String registerUser(@Valid @ModelAttribute("user") User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "registrationForm"; } // Process registration logic return "registrationSuccess"; } }
(Thymeleaf - registrationForm.html)
<form th:object="${user}" th:action="@{/register}" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" th:field="*{username}" required /> <span th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span> <button type="submit">Register</button> </form>
Custom Regular Expression Validation in Spring MVC:
Description: This example demonstrates how to create custom regular expression validations in a Spring MVC application.
Code Snippet: (Custom Validator)
@Component public class CustomValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return User.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; if (!user.getUsername().matches("^[a-zA-Z0-9]{5,10}$")) { errors.rejectValue("username", "Invalid username format"); } } }
(Controller)
@Controller public class UserController { @Autowired private CustomValidator customValidator; @InitBinder public void initBinder(WebDataBinder binder) { binder.addValidators(customValidator); } // Rest of the controller code }
Thymeleaf Regular Expression Validation in Spring MVC:
Description: This example demonstrates Thymeleaf integration for regular expression validation in a Spring MVC application.
Code Snippet: (Thymeleaf template)
<form th:object="${user}" th:action="@{/register}" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" th:field="*{username}" required pattern="^[a-zA-Z0-9]{5,10}$" /> <span th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span> <button type="submit">Register</button> </form>