Spring Boot Validation: Guard Your API (Beginner Guide)
Learn input validation in Spring Boot: field annotations like @NotBlank and @Email, triggering checks with @Valid, the validation starter, and returning clean error messages.
Never trust data from the outside world. Users mistype emails, leave fields blank, and send malformed requests — and sometimes people send bad data on purpose. Validation is how your API politely rejects invalid input before it causes problems. Spring Boot makes this remarkably clean with a set of simple annotations. This lesson shows you how to guard your endpoints properly.
Why validation matters
Imagine a "create user" endpoint. Without validation, someone could send an empty name, an invalid email, or a negative age — and your app would happily save the garbage, or crash later when it hits that bad data. Validation catches these problems at the door and returns a clear error, keeping your database clean and your app robust. It's not optional in real applications; it's essential.
Step 1: Add validation rules to your fields
You declare the rules right on your class fields using annotations from the Bean Validation standard. They read almost like plain English:
public class UserRequest { @NotBlank(message = "Name is required") private String name; @NotBlank @Email(message = "Must be a valid email") private String email; @Min(value = 18, message = "Must be at least 18") @Max(120) private int age; @Size(min = 8, message = "Password must be 8+ characters") private String password; }
The validation annotations you'll use most
| Annotation | Checks that… |
|---|---|
@NotNull |
the value isn't null |
@NotBlank |
a string isn't null or empty/whitespace |
@Email |
a string is a valid email format |
@Size(min,max) |
a string/list length is in range |
@Min / @Max |
a number is within bounds |
@Pattern(regexp) |
a string matches a regex (e.g. phone) |
Step 2: Trigger validation with @Valid
Declaring the rules isn't enough — you tell Spring to actually check them by adding @Valid before the @RequestBody parameter in your controller:
@PostMapping("/api/users") public User create(@Valid @RequestBody UserRequest request) { return service.save(request); }
Now, before your method even runs, Spring checks the incoming data against all the rules. If everything passes, your method executes normally. If anything fails, Spring stops and automatically returns a 400 Bad Request — your save is never called with bad data. That one @Valid is the switch that turns your rules on.
spring-boot-starter-validation. If your @Valid annotations seem to be ignored, this dependency is almost certainly missing from your project — add it and they'll spring to life. This is the #1 "why isn't my validation working?" cause.
Step 3: Return friendly error messages
By default, a validation failure returns a somewhat technical error. To give clients clean, helpful messages, you catch the validation exception in one place and format it. Here's the pattern (you'll learn this more fully in the next lesson on exception handling):
@RestControllerAdvice public class ValidationHandler { @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String,String> handle(MethodArgumentNotValidException ex) { Map<String,String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(err -> errors.put(err.getField(), err.getDefaultMessage())); return errors; // e.g. { "email": "Must be a valid email" } } }
Now a client that sends a bad email gets a tidy JSON response telling them exactly which field was wrong and why — a much better experience than a cryptic stack trace.
Validation is one of those things beginners skip and regret later — I certainly did, and paid for it with a database full of junk records early on. The habit that saved me: treat every piece of data coming from outside as untrusted, and validate it at the boundary (the controller) before it goes any deeper. The annotations make it almost effortless, so there's really no excuse. On this website, every form submission and API request is validated this way before anything touches the database. Add @Valid and a few field annotations from day one, and you'll build far more robust apps.
Key takeaways
- Validate all external input at the boundary — never trust incoming data.
- Declare rules with field annotations (
@NotBlank,@Email,@Size,@Min/@Max,@Pattern). - Add
@Validbefore@RequestBodyto trigger the checks; failures auto-return 400 Bad Request. - Include
spring-boot-starter-validation, and format errors centrally with@RestControllerAdvice.
← Previous: Spring Lesson 6 — Spring Data JPA
Next: Spring Lesson 8 — Exception Handling →
↑ Back to the Spring Boot roadmap