Sub topic 8
Validating a request body with @Valid
This chapter assumes you have a Spring Boot 3 web project that runs, and that you can read a controller method with @RequestBody. It also assumes you know what a Java record is and what an HTTP 400 status means. The previous chapter showed how Jackson turns JSON into a record. Here you will make Spring reject a body that parses correctly but contains values your application cannot accept.
Parsing is not validating
Jackson only checks that the JSON is well formed and that the values can be stored in the target types. Take this body:
{"title": "", "author": null, "pages": -5}Jackson accepts it. The title is an empty string, the author is null, and -5 is a valid int. Without validation, these values reach your service and may end up in the database.
Bean Validation is a standard Java specification (Jakarta Validation) that lets you declare rules as annotations. Hibernate Validator is the implementation Spring Boot uses. Spring MVC runs these rules after Jackson has built the object and before your method body runs.
Adding the dependency
Since Spring Boot 2.3, spring-boot-starter-web no longer includes the validator. You need the validation starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>The Gradle equivalent is implementation 'org.springframework.boot:spring-boot-starter-validation'.
Declaring constraints on a record
Put constraint annotations on the record components. Spring Boot 3 uses the jakarta.validation.constraints package, not javax.
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author,
@NotNull @Positive Integer pages,
@Min(1450) Integer year) {}Annotations on a record component are propagated to the field, accessor, and constructor parameter, so the validator finds them. Several constraints can sit on one component, and all of them are checked.
The most common constraints are:
| Annotation | Passes when | Notes |
|---|---|---|
| `@NotNull` | The value is not `null` | Accepts an empty string |
| `@NotEmpty` | Not `null` and length or size above 0 | Strings, collections, maps, arrays |
| `@NotBlank` | Not `null` and contains a non-whitespace character | Strings only |
| `@Size(min, max)` | Length or size is in range | `null` passes |
| `@Positive`, `@PositiveOrZero` | Number is above 0 (or at least 0) | `null` passes |
| `@Min`, `@Max` | Number is within the bound | `null` passes |
| `@Email` | Looks like an email address | `null` passes, and the check is lenient |
| `@Pattern(regexp)` | Whole string matches the regex | `null` passes |
| `@Past`, `@Future` | Date is before or after now | `null` passes |
Most constraints treat null as valid. The idea is that "is it present?" and "is it well formed?" are separate questions. To require a value that must also satisfy another rule, combine @NotNull (or @NotBlank) with the second constraint, as pages does above.
Triggering validation with @Valid
Constraints do nothing until something asks the validator to check the object. On a controller method, that something is @Valid placed on the @RequestBody parameter:
@PostMapping
public ResponseEntity<Book> create(@Valid @RequestBody CreateBookRequest request) {
Book saved = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}If you prefer, Spring's own @Validated works in the same position. The difference between the two matters later, when we reach validation groups and parameter validation.
What happens inside the request
The order of events explains most of the errors you will see.
Two different exceptions can come from the same request, and they mean different things:
HttpMessageNotReadableExceptionmeans the body could not be turned into the object. Examples are a missing closing brace,"pages": "many"for anInteger, or an empty body when one is required.MethodArgumentNotValidExceptionmeans the object was built, but one or more constraints failed. It carries aBindingResultthat lists every failing field.
The validator collects all violations in one pass. A client that sends three bad fields gets three errors, not one.
Choosing wrapper types over primitives
Look at the pages component. It is Integer, not int. The reason is what Jackson does with a missing field.
With int pages, a body that omits pages produces 0. The record is built with the primitive default, and @Positive then reports "must be greater than 0". The client sees a confusing message about a value it never sent. With Integer pages and @NotNull, the missing field stays null and you can report that it is required.
Use wrapper types (Integer, Long, Boolean) for any field where "absent" is different from "zero" or "false".
Validating nested objects and collections
Validation does not descend into nested objects by itself. You mark the nested component with @Valid:
public record CreateOrderRequest(
@NotBlank String customerEmail,
@NotEmpty @Valid List<@Valid OrderLine> lines) {}
public record OrderLine(
@NotBlank String isbn,
@Positive int quantity) {}The @Valid on the list triggers validation of the list as a property. The @Valid on the type argument tells the validator to check each element. For a single nested object, write @Valid Address address. Without these markers, a bad OrderLine inside a valid order passes unchecked. This is one of the most frequent gaps in real projects.
Field names in the errors use a path, such as lines[1].quantity, so a client can find the exact element.
Custom messages
Each constraint has a message attribute. Use it when the default text is not suitable for your API:
public record CreateBookRequest(
@NotBlank(message = "title is required") String title,
@NotBlank(message = "author is required") String author,
@NotNull(message = "pages is required")
@Positive(message = "pages must be greater than zero") Integer pages) {}The defaults, such as "must not be blank", are localized by Hibernate Validator based on the request locale. If you hard-code an English message, you give that up. For a public API that needs translations, put the key in braces, for example message = "{book.title.required}", and define it in ValidationMessages.properties.
Taking control with BindingResult
If you add a BindingResult parameter directly after the validated argument, Spring stops throwing the exception and passes the errors to your method instead:
@PostMapping("/manual")
public ResponseEntity<?> createManual(@Valid @RequestBody CreateBookRequest request,
BindingResult result) {
if (result.hasErrors()) {
return ResponseEntity.badRequest().body(result.getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.toList());
}
return ResponseEntity.ok(service.create(request));
}This works, but it repeats the error handling in every method, and forgetting the check lets invalid data through. The next chapters handle errors in one central place instead, so treat BindingResult as a tool for unusual cases.
What the client sees
Without any error handler, a failed validation still returns status 400. The body depends on your configuration. With the @RestControllerAdvice from the plan, which reads the field errors from MethodArgumentNotValidException, a bad request looks like this:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Ursula K. Le Guin","pages":-5}'{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request body failed validation",
"instance": "/api/books",
"errors": {
"title": "must not be blank",
"pages": "must be greater than 0"
}
}The handler is covered in detail in the chapter on binding errors. Here it is enough to know that ex.getBindingResult().getFieldErrors() is where the per-field messages come from.
Common mistakes
- Forgetting
@Valid. The constraints sit on the record, but the parameter has no@Valid. Nothing is checked, and the request succeeds with bad data. - Missing starter. See the warning above. Check the dependency first when validation seems to be ignored.
- Using
@NotNullon a string that must have text. An empty string passes@NotNull. Use@NotBlank. - Using
@NotBlankon a non-string. Applying it to anIntegerthrows aUnexpectedTypeExceptionat runtime, which becomes a 500. Use@NotNull. - Not marking nested objects. Child records need
@Validon the parent's component. - Validating the entity instead of the request. Put constraints on the request record that the client sends. Your JPA entity can carry its own rules, but mixing the two makes request errors depend on persistence details.
- Treating validation as business logic. Constraints check the shape of a single request. Checks such as "this ISBN already exists" need the database and belong in the service layer.
Summary of the working model
Jackson builds the object, the validator checks the constraints you declared, and Spring throws MethodArgumentNotValidException if any fail. @Valid on the @RequestBody parameter turns that process on, and @Valid on nested components extends it inward. Choose wrapper types so that missing values are visible, combine @NotNull or @NotBlank with other constraints because most constraints accept null, and send every failure to one central handler.
Exercise
A client posts {"title":"Dune","author":"Frank Herbert"} to an endpoint that takes @Valid @RequestBody CreateBookRequest, where the record declares @Positive int pages. The request returns 400 with the message "must be greater than 0" for pages. Why does this happen, and what two changes make the error say that pages is required?
Show answer
The field is missing, and Jackson fills a primitive int with its default value 0. @Positive then rejects 0, so the client gets a message about a value it never sent. Change the component to the wrapper type Integer so a missing field stays null, and add @NotNull (with a message such as "pages is required"), since @Positive treats null as valid.
Exercise
A CreateOrderRequest has List<OrderLine> lines, and OrderLine has @Positive int quantity. A request contains a line with quantity -1, yet it is accepted. What is missing?
Show answer
Validation does not cascade into nested objects automatically. Add @Valid to the lines component, and also to the element type (List<@Valid OrderLine>), so the validator checks each OrderLine. Errors will then appear with paths such as lines[0].quantity.