0
0
Spring Bootframework~5 mins

@Email and @Pattern in Spring Boot

Choose your learning style9 modes available
Introduction

These annotations help check if text inputs follow rules like a valid email or a specific pattern. They make sure data is correct before saving or using it.

When you want to check if a user's email address is valid before saving it.
When you need to make sure a phone number matches a certain format.
When you want to validate form inputs like postal codes or usernames.
When you want to avoid bad data entering your system by checking patterns.
When you want to give users quick feedback on wrong input formats.
Syntax
Spring Boot
@Email(message = "error message")
@Pattern(regexp = "regex", message = "error message")

@Email checks if a string looks like a real email address.

@Pattern checks if a string matches the given regular expression (regex).

Examples
This checks if the email field contains a valid email format.
Spring Boot
@Email(message = "Please enter a valid email")
private String email;
This checks if the phoneNumber has exactly 10 digits.
Spring Boot
@Pattern(regexp = "\\d{10}", message = "Must be 10 digits")
private String phoneNumber;
This ensures the username contains only letters and numbers.
Spring Boot
@Pattern(regexp = "^[A-Za-z0-9]+$", message = "Only letters and numbers allowed")
private String username;
Sample Program

This program creates a User with an email and phone number. It uses @Email and @Pattern to check if the inputs are correct. If all are valid, it prints a success message. Otherwise, it prints the error messages.

Spring Boot
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.Valid;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.ConstraintViolation;
import java.util.Set;

public class User {
    @Email(message = "Invalid email format")
    private String email;

    @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "Phone must be in format XXX-XXX-XXXX")
    private String phone;

    public User(String email, String phone) {
        this.email = email;
        this.phone = phone;
    }

    public static void main(String[] args) {
        User user = new User("test@example.com", "123-456-7890");

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<User>> violations = validator.validate(user);

        if (violations.isEmpty()) {
            System.out.println("All inputs are valid.");
        } else {
            for (ConstraintViolation<User> violation : violations) {
                System.out.println(violation.getMessage());
            }
        }
    }
}
OutputSuccess
Important Notes

Remember to add the dependency for jakarta.validation (Bean Validation) in your project to use these annotations.

@Email only checks the format, not if the email actually exists.

Regex in @Pattern must be double escaped in Java strings (\\).

Summary

@Email and @Pattern help check if text inputs follow rules.

Use @Email for emails and @Pattern for custom formats.

They improve data quality and user feedback in your apps.