Spring Boot Validation with @Pattern Annotation

Hi everyone 👋 Continuing the Spring Boot Validation Series Part 30👇 📌 Validation Annotation – @Pattern The @Pattern annotation is used to validate a field using a regular expression (regex) 👇 🔹 Why do we use @Pattern? Sometimes we need to validate format like: Email format Phone number Password rules Only alphabets / numbers 👉 @Pattern helps enforce these rules. 🔹 Simple Example - public class User { @Pattern(regexp = "^[a-zA-Z]+$") private String name; } 👉 Allows only alphabets 👉 If invalid → validation fails ❌ 🔹 Email Example - @Pattern(regexp = "^[A-Za-z0-9+_.-]+@(.+)$") private String email; 🔹 Important Point 👉 @Pattern works only with String fields 👉 It does NOT check null ❌ So often combined with: @NotNull @Pattern(regexp = "your-regex") private String field; 🔹 In simple words @Pattern checks if a value follows a specific format. 👉 🧠 Quick Understanding - Uses regex for validation - Works only on String - Used for format validation - Often combined with @NotNull or @NotBlank #SpringBoot #Java #Validation #PatternAnnotation #BackendDevelopment #LearningInPublic

To view or add a comment, sign in

Explore content categories