Spring Boot Pattern Annotation Guide: How to Use Pattern Validation in Spring for Beginners
Student
"How can I validate string inputs using regular expressions in Spring Boot forms?"
Teacher
"In Spring validation basics, you can use the @Pattern annotation to enforce strict regular expression constraints on your data transfer objects."
Student
"What is the easiest way to implement this in a real Spring controller?"
Teacher
"Let us explore the step-by-step guide on how to use the @Pattern annotation in Spring Boot!"
1. Introduction to the Spring Pattern Annotation
Welcome to this comprehensive tutorial designed for Spring Boot beginners. When you are building robust enterprise web applications, input validation is a critical security layer. Validating user submissions prevents malformed data from entering your database or services.
The @Pattern annotation is a powerful validation constraint provided by the Jakarta Bean Validation API, which Spring Boot integrates seamlessly. It allows you to specify a regular expression (regex) that the annotated string property must match to be considered valid.
2. Setting Up Dependencies for Validation in Spring Boot
Before you can use validation annotations like @Pattern, you must ensure your project includes the Spring Boot Validation starter dependency in your build configuration file.
Let us look at how to declare this dependency in a Maven pom.xml file for your beginner project setup.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Execution result:
Validation starter dependency added successfully to project build path.
3. Creating a DTO with the Pattern Annotation
Once your dependencies are ready, you can apply the @Pattern annotation inside your form backing objects or Data Transfer Objects (DTO). You specify the regex pattern string and a custom error message.
Let us create a user registration form model where the username field allows only alphanumeric characters.
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.NotBlank;
public class UserFormDto {
@NotBlank(message = "Username cannot be blank")
@Pattern(regexp = "^[a-zA-Z0-9]{4,12}$", message = "Username must be 4 to 12 alphanumeric characters")
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Execution result:
DTO class configured with alphanumeric pattern constraint.
4. Validating Phone Numbers with Regex Patterns
Another common use case for the @Pattern annotation is validating specific formats like telephone numbers, postal codes, or employee identification codes.
Let us write another model field that verifies a standard phone number format using a custom regular expression.
import jakarta.validation.constraints.Pattern;
public class ContactFormDto {
@Pattern(regexp = "^\\d{3}-\\d{3}-\\d{4}$", message = "Phone number must follow XXX-XXX-XXXX format")
private String phoneNumber;
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Execution result:
Phone number pattern validation rule registered successfully.
5. Handling Validation in Spring REST Controllers
To activate the validation rules defined in your DTO classes during an incoming HTTP request, you must use the @Valid or @Validated annotation inside your REST controller method parameters.
Let us look at a controller snippet showing how to capture validation errors when processing form submissions.
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
@RestController
public class UserController {
@PostMapping("/api/users")
public ResponseEntity<String> registerUser(@Valid @RequestBody UserFormDto userForm) {
return ResponseEntity.ok("Validation passed successfully!");
}
}
Execution result:
HTTP 200 OK returned on valid payload; validation errors intercepted automatically if pattern fails.
6. Best Practices for Pattern Validation in Spring Boot
When writing code with the @Pattern annotation, keep these helpful tips in mind to avoid common pitfalls:
- Always escape backslashes correctly in Java string literals when writing regex patterns (e.g., use
\\\\dinstead of\\dif defining strings externally). - Provide clear, user-friendly error messages in the message attribute so frontend clients know how to fix input mistakes.
- Combine
@Patternwith@NotBlankor@NotNullif empty values require separate error reporting.
By following these best practices, your Spring Boot input validation layer will remain secure, clean, and reliable.
Summary
In this comprehensive guide, we explored how to use the @Pattern annotation in Spring Boot for robust input validation. We started with the foundational concepts of regular expression constraints, learned how to include the validation starter dependency in Maven projects, and built practical Data Transfer Objects (DTOs) for user registration and contact forms. Furthermore, we examined how to trigger validation checks inside Spring REST controllers using the @Valid annotation and reviewed crucial best practices such as proper backslash escaping and clear error messaging. Mastering these validation basics ensures your enterprise applications remain secure, reliable, and clean.
Student
"Now that we have covered everything about the @Pattern annotation, how should I think about combining multiple constraints in a real application?"
Teacher
"You can combine @Pattern with annotations like @Size or @Email to build multi-layered validation rules on your properties, making your DTO models extremely resilient against invalid user entries."
Student
"That makes total sense! I feel ready to apply regex validation safely in my Spring Boot projects."
Teacher
"Fantastic! Keep practicing and testing different regular expression patterns to build confidence in your backend development journey."