How do you validate request data in Spring Boot?
Options
- Only with
ifstatements repeated in every controller - Constraint annotations like
@NotBlank, plus@Valid(Correct option) - With CSS rules that are applied on the client side
- 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.