public class User { @Email private String email; // getters and setters } @PostMapping("/register") public ResponseEntity<String> registerUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User registered"); }
The @Email annotation triggers validation on the email field. When used with @Valid in the controller, Spring Boot automatically checks the input. If the email is invalid, it returns a 400 Bad Request with validation error details.
public class Address { @Pattern(regexp = "???", message = "Invalid ZIP code") private String zipCode; // getters and setters }
The regex "\\d{5}" matches exactly 5 digits. The double backslash is needed in Java strings to represent a single backslash in the regex.
public class Contact { @Email private String email; // getters and setters } @PostMapping("/contact") public String submitContact(@RequestBody Contact contact) { return "Received"; }
Validation annotations like @Email require the @Valid annotation on the controller method parameter to activate validation. Without @Valid, the annotations are ignored.
@Email is a specialized annotation for email format validation. @Pattern is a general-purpose annotation that validates strings against any regex pattern you provide.
public class Location { @Pattern(regexp = "\\d{5}", message = "ZIP code must be 5 digits") private String zipCode; // getters and setters } @PostMapping("/location") public ResponseEntity<String> addLocation(@Valid @RequestBody Location location) { return ResponseEntity.ok("Location added"); }
The message attribute in @Pattern defines the exact error message returned when validation fails.