Card 02/ 06

ExampleDifficulty: Intermediate1 min

Bean Validation Example: @Valid Rejects a Bad Request

An empty pickup and zero passengers are refused with 400 before the method body runs.

@Valid on a controller parameter tells Spring to check that parameter's constraint annotations before calling the method. A request that breaks any of them is rejected with 400 Bad Request, and the method body never runs.

A RideRequest record with two constraints, @NotBlank on pickup and @Min(1) on passengers, received with @Valid:

java
@PostMapping("/rides")
ResponseEntity<String> createRide(@Valid @RequestBody RideRequest request) {
    return ResponseEntity.ok("created: " + request);
}

A request with an empty pickup and zero passengers:

text
POST /rides, body {"pickup":"","passengers":0}
-> 400 Bad Request
run in a container: the method body never runs

Both fields break a rule: the empty pickup fails @NotBlank, and 0 passengers fails @Min(1). Spring checked them right after converting the JSON into a RideRequest, found two violations, and answered 400 before createRide was called. Spring Boot's default 400 response does not list which fields failed, so a client only learns that something was wrong; returning the field errors takes a handler of your own.

So @Valid is the switch that turns the annotations into a check. With it in place, the method body can assume every constraint holds.