How to Use @Pattern Annotation in Spring Boot for Input Validation
In Spring Boot, use the
@Pattern annotation on a string field to validate its value against a regular expression. This annotation is part of the javax.validation.constraints package and works with Spring's validation framework to ensure input matches the specified pattern before processing.Syntax
The @Pattern annotation requires a regexp attribute to define the regular expression for validation. Optionally, you can provide a message to customize the error message shown when validation fails.
- regexp: The regex pattern the string must match.
- message: Custom error message on validation failure.
- flags: Optional regex flags like CASE_INSENSITIVE.
java
import javax.validation.constraints.Pattern; public class UserInput { @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Only alphanumeric characters are allowed") private String username; // getters and setters }
Example
This example shows a Spring Boot REST controller validating a user input object with a @Pattern annotation. If the input does not match the pattern, Spring returns a validation error automatically.
java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.Pattern; @SpringBootApplication public class PatternValidationApp { public static void main(String[] args) { SpringApplication.run(PatternValidationApp.class, args); } } @RestController @Validated class UserController { @PostMapping("/users") public String createUser(@Valid @RequestBody UserInput input) { return "User " + input.getUsername() + " is valid!"; } } class UserInput { @Pattern(regexp = "^[a-zA-Z0-9]{5,10}$", message = "Username must be 5-10 alphanumeric characters") private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
Output
POST /users with JSON {"username":"user123"} returns: "User user123 is valid!"
POST /users with JSON {"username":"u!"} returns HTTP 400 with validation error message: "Username must be 5-10 alphanumeric characters"
Common Pitfalls
- Not using
@Validon the controller method parameter will skip validation. - Incorrect regex patterns can cause unexpected validation results.
- For non-string fields,
@Patterndoes not apply; use other validators. - Missing dependency for validation API or Hibernate Validator can cause runtime errors.
java
/* Wrong: Missing @Valid, validation won't trigger */ @PostMapping("/users") public String createUser(@RequestBody UserInput input) { return "User " + input.getUsername() + " is valid!"; } /* Right: Add @Valid to trigger validation */ @PostMapping("/users") public String createUser(@Valid @RequestBody UserInput input) { return "User " + input.getUsername() + " is valid!"; }
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| regexp | Regular expression pattern to match | "^[a-zA-Z0-9]+$" |
| message | Custom error message on failure | "Invalid input format" |
| flags | Regex flags like CASE_INSENSITIVE | Pattern.Flag.CASE_INSENSITIVE |
Key Takeaways
Use @Pattern on string fields to enforce regex-based validation in Spring Boot.
Always add @Valid on controller method parameters to activate validation.
Customize error messages with the message attribute for better user feedback.
Ensure your regex pattern matches the expected input format precisely.
Include validation dependencies like Hibernate Validator in your project.