Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-22

How do you validate request data in Spring Boot?

Options

  1. Only with if statements repeated in every controller
  2. Constraint annotations like @NotBlank, plus @Valid (Correct option)
  3. With CSS rules that are applied on the client side
  4. It is not possible to validate requests in Spring

Answer

Add Bean Validation annotations (@NotBlank, @Email, @Size...) on the fields and use @Valid on the controller parameter

Why

Bean Validation (Jakarta Validation) lets you declare rules on fields. Put @Valid before the @RequestBody parameter and Spring checks the rules before running your method. On failure it throws MethodArgumentNotValidException, which you can convert to a 400 response.

The starter is spring-boot-starter-validation.

Never trust client data: validate on the server even if the front-end also validates.

public record CreateUserRequest(
    @NotBlank String name,
    @Email @NotBlank String email,
    @Size(min = 8) String password
) {}

Remember

@Valid + constraint annotations = declarative validation.

Key terms

Practice this question in Repaso