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.
@Email and @Pattern in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
@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).
@Email(message = "Please enter a valid email")
private String email;@Pattern(regexp = "\\d{10}", message = "Must be 10 digits") private String phoneNumber;
@Pattern(regexp = "^[A-Za-z0-9]+$", message = "Only letters and numbers allowed") private String username;
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.
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()); } } } }
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 (\\).
@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.
Practice
@Email annotation in Spring Boot validation?Solution
Step 1: Understand the role of @Email
The@Emailannotation is designed to validate that a string looks like a proper email address format.Step 2: Compare with other annotations
@Patternis used for custom regex,@NotEmptyensures non-empty, and no annotation converts case automatically.Final Answer:
To check if a string is a valid email format -> Option DQuick Check:
@Email = Valid email format [OK]
- Confusing @Email with @Pattern for custom regex
- Thinking @Email checks if field is empty
- Assuming @Email changes string content
@Pattern to allow only digits in a Spring Boot entity field?Solution
Step 1: Check the correct attribute name
The correct attribute for@Patternisregexp, notregexorpattern.Step 2: Validate the regex for digits
The regex\\d+matches one or more digits. @Pattern(regexp = "\\d+") uses correct syntax and regex.Final Answer:
@Pattern(regexp = "\\d+") -> Option BQuick Check:
@Pattern uses regexp attribute [OK]
- Using 'regex' instead of 'regexp' attribute
- Using incorrect regex syntax
- Confusing @Pattern attribute names
@Email @Pattern(regexp = ".+@example\\.com$") private String email;
What happens if the user inputs
user@test.com?Solution
Step 1: Understand @Email validation
@Email checks if the input looks like an email. 'user@test.com' is a valid email format, so it passes this check.Step 2: Understand @Pattern validation
@Pattern requires the email to end with '@example.com'. 'user@test.com' ends with '@test.com', so it fails this pattern check.Final Answer:
Validation fails because email does not end with @example.com -> Option AQuick Check:
@Pattern restricts domain, so input fails [OK]
- Assuming @Email alone validates domain
- Thinking @Pattern is ignored if @Email passes
- Believing @Email and @Pattern conflict
@Email @Pattern(regexp = "[a-zA-Z]+") private String userEmail;
Why might this validation cause unexpected failures for typical emails?
Solution
Step 1: Analyze the regex pattern
The regex[a-zA-Z]+allows only letters, no digits, dots, or @ symbols which are common in emails.Step 2: Understand impact on email validation
This pattern blocks valid email characters like digits, dots, and '@', causing valid emails to fail validation.Final Answer:
Because the regex only allows letters, blocking digits and symbols in emails -> Option AQuick Check:
Regex must allow email characters [OK]
- Assuming @Email restricts uppercase letters
- Thinking @Pattern requires empty field
- Believing @Email and @Pattern conflict
mycompany.com domain. Which annotation setup is correct?Solution
Step 1: Use @Email for email format validation
@Email ensures the string is a valid email format regardless of domain.Step 2: Use @Pattern to restrict domain
@Pattern with regex.+@mycompany\\.com$ensures the email ends with '@mycompany.com'.Step 3: Check other options
@Email(regexp = ".+@mycompany\\.com$") is invalid because @Email does not accept regexp attribute. @Pattern(regexp = ".+@mycompany\\.com$") misses email format check. @Email @Pattern(regexp = "^mycompany.com$") regex is incorrect for email domain.Final Answer:
@Email @Pattern(regexp = ".+@mycompany\\.com$") -> Option CQuick Check:
Combine @Email and @Pattern for domain restriction [OK]
- Trying to put regexp inside @Email
- Using incomplete regex that misses email format
- Incorrect regex anchors for domain
