Sub topic 10
Validating input with @Valid
This chapter covers how Spring MVC checks request data before your controller logic runs. It assumes you can write a @RestController, accept JSON with @RequestBody, and read basic annotations on Java records. It also assumes you have a Spring Boot web project set up with Maven or Gradle.
Why validate at the edge
A controller receives data from clients you do not control. If you pass that data straight to the service layer, bad values reach your business logic and your database. A blank title, a negative page size, or a missing field then fails deep inside the application, with an unclear error.
Validation at the controller boundary rejects bad input early. The client gets a 400 Bad Request that says which field was wrong. Your service code can then assume the data has the right shape.
Spring uses Bean Validation for this. Bean Validation is a Java standard (Jakarta Validation) that lets you declare rules as annotations on fields. Hibernate Validator is the reference implementation, and Spring Boot configures it for you when the starter is on the classpath.
Adding the dependency
Spring Boot does not include validation in spring-boot-starter-web. Add the validation starter.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>For Gradle, the equivalent line is implementation 'org.springframework.boot:spring-boot-starter-validation'.
Without this starter, the annotations compile only if some other library brings the API in, and constraints are silently not enforced. Missing validation with no error is the most common setup mistake.
Declaring constraints on a DTO
Put constraints on the request DTO. With a record, the annotations go on the record components.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author) {}
public record BookResponse(long id, String title, String author) {}Common constraints:
| Annotation | Rule | Notes |
|---|---|---|
| `@NotNull` | Value is not null | Allows an empty string |
| `@NotEmpty` | Not null and length or size above 0 | Works on strings, collections, maps, arrays |
| `@NotBlank` | Not null and contains a non-whitespace character | Strings only |
| `@Size(min, max)` | Length or size within bounds | Null passes |
| `@Min`, `@Max` | Numeric bounds | Null passes |
| `@Positive` | Greater than zero | Null passes |
| `@Email` | Looks like an email address | Null passes |
| `@Pattern(regexp)` | Matches a regular expression | Null passes |
Most constraints treat null as valid. If a field is required, combine the constraint with @NotNull or use @NotBlank for strings. For example, @Size(max = 200) alone accepts a missing title.
Triggering validation with @Valid
Constraints do nothing until something asks Spring to check them. Add @Valid to the @RequestBody parameter.
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}The request flows through these steps:
- Jackson converts the JSON body into a
CreateBookRequest. - Spring runs the validator on the object.
- If every constraint passes, the method body runs.
- If any constraint fails, Spring throws
MethodArgumentNotValidExceptionand the method body never runs.
Note the two different failure points. Malformed JSON fails before validation, with a different exception. Both produce a 400 by default, but the messages differ.
What the client sees by default
With no extra configuration, Spring Boot returns a 400 response for a failed validation. The default body is a generic error structure that may omit the field details. To get a consistent, informative body, enable ProblemDetail support for Spring MVC's built-in exceptions.
spring.mvc.problemdetails.enabled=trueWith this property, a failed validation returns a response with Content-Type: application/problem+json and a body like this:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Invalid request content.",
"instance": "/api/books"
}This body tells the client the request was invalid but does not list the failing fields. To report them, handle the exception yourself.
Reporting field errors
Extend your @RestControllerAdvice with a handler for MethodArgumentNotValidException. The exception carries a BindingResult with one FieldError per violated constraint.
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalid(MethodArgumentNotValidException ex) {
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.putIfAbsent(e.getField(), e.getDefaultMessage()));
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return problem;
}
}A request with a blank title and no author now returns:
{
"type": "about:blank",
"title": "Invalid request",
"status": 400,
"detail": "Request validation failed",
"instance": "/api/books",
"errors": {
"title": "must not be blank",
"author": "must not be blank"
}
}The putIfAbsent call keeps only the first message per field. A single field can break several constraints at once, and a Map with put would silently keep the last one.
If you extend ResponseEntityExceptionHandler instead, it already maps this exception and you override handleMethodArgumentNotValid. Do not define both approaches for the same exception type, or Spring will report an ambiguous handler.
Custom messages
Every constraint accepts a message attribute.
public record CreateBookRequest(
@NotBlank(message = "title is required")
@Size(max = 200, message = "title must be at most {max} characters")
String title,
@NotBlank(message = "author is required") String author) {}Placeholders such as {max} are filled from the annotation attributes. For messages that change by locale, use a key like {book.title.required} and define it in ValidationMessages.properties.
Validating nested objects and collections
Validation does not descend into nested objects on its own. Mark the nested property with @Valid too.
public record CreateOrderRequest(
@NotBlank String customer,
@NotEmpty List<@Valid OrderLine> lines) {}
public record OrderLine(
@NotBlank String sku,
@Positive int quantity) {}Here @NotEmpty checks that the list has entries. @Valid on the type argument makes Spring validate each OrderLine. Without it, a line with quantity -5 passes. Field names in errors then include the path, such as lines[0].quantity.
Validating path variables and query parameters
@Valid on a body is not enough for simple parameters. For @RequestParam and @PathVariable, put the constraint directly on the argument.
@GetMapping("/{id}")
public BookResponse get(@PathVariable @Positive long id) {
return service.get(id);
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") @Size(max = 100) String title) {
return service.search(title);
}In Spring Framework 6.1 and later (Spring Boot 3.2 and later), controller method validation is built in. A violation throws HandlerMethodValidationException. With spring.mvc.problemdetails.enabled=true, it becomes a 400 ProblemDetail.
In Spring Boot 3.1 and earlier, you must also add @Validated to the controller class. Violations then throw ConstraintViolationException, which you handle with your own @ExceptionHandler. Check your version before debugging a constraint that appears to be ignored.
In Spring Framework 6.1 and later, adding @Validated at class level switches back to the older AOP proxy behavior. Leave it off unless you need that.
Groups of constraints, briefly
Sometimes create and update requests need different rules. Bean Validation supports validation groups, but they add complexity. Two separate DTOs are usually simpler:
CreateBookRequestrequires all fields.UpdateBookRequesthas its own rules.
Prefer separate DTOs unless the rules overlap almost completely.
Common errors
- Constraints are ignored. Check the starter dependency, the
@Validon the parameter, and@Validon nested fields. @Sizeor@Minaccepts null. Add@NotNullor@NotBlank.@NotNullon a string accepts"". Use@NotBlankfor text input.- Primitive fields cannot be missing. A
longfield defaults to0when absent from JSON, so@NotNullnever fails. UseLongwhen "absent" must be detectable. - Validation errors expose internals. Return field names and messages from the DTO, not exception stack traces or class names.
- Business rules in annotations. Rules that need a database, such as "title must be unique", belong in the service layer. Throw a domain exception and handle it in your
@RestControllerAdvice, typically as409 Conflict.
Exercises
Exercise
A DTO has the field @Size(max = 50) String nickname. A client sends {} with no nickname. Does validation fail, and what would you change if nickname is required?
Show answer
Validation does not fail, because @Size treats null as valid. Add @NotBlank (or @NotNull) to the field so a missing or blank nickname is rejected.
Exercise
You add @Positive int quantity to an OrderLine record inside List<OrderLine> lines on the request DTO, but a request with quantity -5 returns 201. Name the likely cause and the fix.
Show answer
Validation does not cascade into nested objects. Change the list to List<@Valid OrderLine> lines, and make sure the controller parameter itself has @Valid @RequestBody.
Exercise
Which exception does Spring throw when a @Valid @RequestBody argument fails validation, and how can you return the failing field names in a ProblemDetail?
Show answer
It throws MethodArgumentNotValidException. In a @RestControllerAdvice, handle it, read ex.getBindingResult().getFieldErrors(), and add the field-to-message map with problem.setProperty("errors", errors).