Sub topic 4
Triggering validation with @Valid
This chapter assumes you have the spring-boot-starter-validation dependency and a request DTO with constraint annotations, as in the earlier chapters. It also assumes you can write a basic @RestController.
Constraints do nothing on their own
Annotations such as @NotBlank and @Min only describe rules. Nothing checks them until something asks a validator to run. In a Spring MVC controller, that trigger is the @Valid annotation on a handler method parameter.
Here is the DTO from the previous chapter:
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@NotNull @Min(18) Integer age) {
}Add @Valid next to @RequestBody to trigger validation:
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public ResponseEntity<Void> create(@Valid @RequestBody CreateUserRequest request) {
// request has passed validation here
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}What happens during a request
Spring does the work while it resolves the method arguments, before your method body runs.
Two details follow from this order:
- Conversion comes first. Malformed JSON, or a string where a number is expected, fails with
HttpMessageNotReadableExceptionbefore any constraint is checked. - Validation failure throws
MethodArgumentNotValidException. Spring Boot's default handling turns it into a 400 response. The next chapter covers the exception in detail.
You can check the behavior with a request that breaks several rules:
curl -i -X POST http://localhost:8080/users \
-H "Content-Type: application/json" \
-d '{"name":"","email":"not-an-email","age":12}'This returns 400 Bad Request, and the controller method never runs.
Common mistakes
- Forgetting
@Valid. The request is accepted and the invalid object reaches your code. There is no warning, so test with a bad payload. - Missing starter. Without
spring-boot-starter-validation, no validator is configured, so the constraints have no effect. Recent Spring Boot versions don't add the starter through the web starter. - Annotating the wrong thing.
@Validmust be on the parameter, not on the class or the DTO type. - Expecting null bodies to be validated. A missing body fails with
HttpMessageNotReadableException, because@RequestBodyis required by default.
@Valid or @Validated
Both annotations can trigger validation on a method parameter that is a request body. @Valid is the standard Jakarta annotation. @Validated is Spring's own, and it also supports validation groups, which a later chapter covers. For plain body validation, prefer @Valid.
Exercise
A client posts {"name":"Ana","email":"[email protected]","age":12} to a controller whose method parameter is @RequestBody CreateUserRequest request, without @Valid. The DTO has @Min(18) on age. What response does the client get, and why?
Show answer
The client gets 201 Created (or whatever the method returns), because the JSON converts to a valid object and nothing runs the constraint check. The @Min(18) rule is never evaluated. Adding @Valid before @RequestBody makes Spring check the constraints and respond with 400.