Sub topic 10
Validating input with @Valid
This chapter assumes you can write a @RestController that accepts a JSON body with @RequestBody, and that you know what a record is. It covers how Spring checks incoming data before your controller logic runs.
Why validate at the edge
A client can send anything: a missing title, a 5,000-character name, or null. Checking this at the controller boundary rejects bad input early. Your service layer can then assume the data is well formed.
Spring uses Bean Validation (the Jakarta Validation standard) for this. You declare rules as annotations on the DTO. Spring runs the rules when the argument is marked @Valid.
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>Without it, the annotations compile only if another library brings them in, and nothing enforces them. This is a common cause of "my validation does nothing".
Constraints on a record DTO
Put the constraints on the record components:
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 |
|---|---|
| `@NotNull` | Value must not be `null`. |
| `@NotBlank` | String must contain at least one non-whitespace character. |
| `@Size(max = 200)` | String length or collection size within bounds. |
| `@Min`, `@Max` | Numeric range. |
| `@Email` | Looks like an email address. |
@NotBlank already rejects null, so you do not need @NotNull beside it.
Triggering validation with @Valid
Constraints do nothing until you ask 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);
}If any constraint fails, Spring throws MethodArgumentNotValidException before create is called. By default Spring Boot turns this into a 400 Bad Request.
Making the error response useful
The default 400 body is not very informative. Turn on RFC 9457 ProblemDetail responses for Spring MVC's built-in exceptions:
spring.mvc.problemdetails.enabled=trueNow a request with a blank title returns a ProblemDetail JSON body with status 400 instead of Spring's older error format. If you want to list each failing field, handle MethodArgumentNotValidException in your @RestControllerAdvice class and add the field errors to the problem. The next chapter covers that class in full.
Common errors
- Forgetting
@Valid. The constraints are ignored and invalid data reaches your service. - Missing starter. Validation is silently not performed, as described above.
- Validating query parameters.
@Validon a DTO handles request bodies. To check@RequestParamor@PathVariablevalues with constraints such as@Min(1), put@Validatedon the controller class. Failures there raiseHandlerMethodValidationExceptionin Spring 6.1 and later, orConstraintViolationExceptionin earlier versions. - Malformed JSON. A body that cannot be parsed fails before validation runs. It produces a 400 from
HttpMessageNotReadableException, not a constraint error.
Exercise
A POST endpoint accepts @RequestBody CreateBookRequest request. The DTO has @NotBlank on title, but a request with "title": "" is accepted and saved. Name two likely causes.
Show answer
First, the parameter is missing @Valid, so Spring never runs the constraints. Second, spring-boot-starter-validation is not on the classpath, so no validator is available to enforce them.