Request validation in Spring Boot looks like a two-annotation job, @NotNull on a field and @Valid on the parameter, but several gaps let invalid data through with no error at all: a missing validation starter, nested objects without their own @Valid, and rules such as “email must be unique” that no annotation can enforce safely. You also have to decide what error body the client sees. A request that skips validation silently is worse than one that fails loudly. Examples target Spring Boot 3.x (Spring Framework 6.1+) with the jakarta.validation annotations from spring-boot-starter-validation.
The setup in one paragraph: starter, constraints, @Valid
Add spring-boot-starter-validation, declare Jakarta constraints such as @NotBlank, @Email, @Positive and @Size on request DTO fields, and annotate the controller parameter with @Valid. Invalid bodies make Spring throw MethodArgumentNotValidException, which Boot turns into a 400; map it to a ProblemDetail that lists field errors. Nested objects and list elements need @Valid too. Since Spring 6.1, constraints directly on @PathVariable and @RequestParam parameters are validated by built-in method validation. Validation checks request shape; rules that need the database belong in the service.
What triggers validation on a body and on a path variable
Request DTOs carry constraints:
public record CreateOrderRequest(
@NotBlank String customerId,
@NotEmpty List<@Valid OrderLineRequest> lines,
@Valid @NotNull Address shippingAddress,
@Size(max = 500) String note) { }
public record OrderLineRequest(
@NotBlank String sku,
@Positive @Max(100) int quantity) { }
public record Address(
@NotBlank String line1,
@NotBlank @Pattern(regexp = "[A-Z]{2}") String country) { }The controller triggers validation with @Valid:
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService orders;
OrderController(OrderService orders) { this.orders = orders; }
@PostMapping
ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest request) {
OrderResponse created = orders.create(request);
return ResponseEntity.created(URI.create("/orders/" + created.id())).body(created);
}
@GetMapping("/{id}")
OrderResponse get(@PathVariable @Positive long id) {
return orders.find(id);
}
}After Jackson deserializes the body, Spring MVC’s argument resolver sees @Valid and calls the Validator that Boot auto-configured (Hibernate Validator). Violations are collected into a BindingResult, and the resolver throws MethodArgumentNotValidException before your method runs. Validation cascades into shippingAddress and into each element of lines only because of the @Valid markers there.
For @Positive long id, Spring 6.1 detects constraint annotations on method parameters and applies method validation automatically, throwing HandlerMethodValidationException (also a 400). On earlier versions you needed @Validated on the controller class, which produced ConstraintViolationException and a 500 unless you mapped it. The switch is made per handler method: if a method with a @Valid @RequestBody also has a constraint directly on another parameter, Spring 6.1 validates the whole method and reports the body’s errors through HandlerMethodValidationException too, so an advice that only overrides handleMethodArgumentNotValid misses them.
Adding validation to an order API
Step 1: Add the starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Since Spring Boot 2.3 it is not included in spring-boot-starter-web. Without it, the jakarta.validation annotations may still compile (if the API jar arrives transitively) but no validator exists, and nothing is checked.
Step 2: Choose the right constraints
@NotNull rejects null only. @NotEmpty also rejects empty strings and collections. @NotBlank also rejects whitespace-only strings. Use primitives (int) carefully: a missing JSON field becomes 0, which @NotNull cannot detect, so prefer Integer with @NotNull when “missing” must be an error, or rely on @Positive as above.
Step 3: Shape the error response
Boot’s default 400 body is generic. Extend ResponseEntityExceptionHandler (see exception advice) or enable spring.mvc.problemdetails.enabled=true, then add the field errors:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
ProblemDetail pd = ex.getBody();
pd.setDetail("Request has invalid fields");
pd.setProperty("errors", ex.getFieldErrors().stream()
.map(f -> Map.of("field", f.getField(), "message", String.valueOf(f.getDefaultMessage())))
.toList());
return ResponseEntity.badRequest().body(pd);
}A request with an empty lines list and a bad country produces:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request has invalid fields",
"instance": "/orders",
"errors": [
{ "field": "lines", "message": "must not be empty" },
{ "field": "shippingAddress.country", "message": "must match \"[A-Z]{2}\"" }
]
}The order of errors is not guaranteed, so clients should not rely on it.
Step 4: Keep business rules in the service
“Customer exists”, “SKU is in stock” and “email not already registered” need the database and can change between validation and save. Check them in the service inside the transaction and throw domain exceptions mapped to 404 or 409. Use database constraints as the final guarantee for uniqueness.
Six gaps that let invalid requests through
- Forgetting
@Validon the controller parameter. Constraints are metadata; something must trigger them. - Forgetting
@Validon nested fields and collection elements. Validation does not cascade by default. - Missing
spring-boot-starter-validation. Without it there is no validator, so nothing is checked and nothing fails. - Validating in the controller with
ifstatements. The checks duplicate the constraints and drift from them over time. - Putting uniqueness checks in a custom constraint that queries the database. It races with concurrent requests and couples validation to persistence.
- Leaving
ConstraintViolationExceptionunmapped on versions before Spring 6.1. Path-variable and query-parameter violations then come back as 500 instead of 400.
A signup form that let empty emails through
Picture a team that adds @NotBlank and @Email to a signup DTO, writes a controller with @RequestBody SignupRequest request, and ships. A month later, analytics show accounts with empty emails.
Three mistakes can stack up this way. The parameter lacks @Valid, so the constraints are decorative. When a reviewer adds @Valid, nested @NotBlank fields in request.profile() are still not checked, because the profile field lacks its own @Valid. And in another service the validation starter is missing altogether, removed during a “trim unused dependencies” pass. (@Email alone would not have helped: it treats an empty string as valid, which is why @NotBlank sits next to it.)
The fix adds @Valid at both levels, restores the starter, and adds a WebMvc test per DTO that sends an invalid payload and asserts a 400 with the expected field names. The empty-email accounts are cleaned up with a migration, and a NOT NULL plus CHECK (email <> '') constraint is added so the database rejects the case even if validation regresses.
A WebMvc test that proves the controller never ran
@WebMvcTest(OrderController.class)
class CreateOrderValidationTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orders;
@Test
void rejectsEmptyLinesAndBadCountry() throws Exception {
String body = """
{"customerId":"c-1","lines":[],
"shippingAddress":{"line1":"1 Main St","country":"usa"}}
""";
mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(body))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[*].field",
containsInAnyOrder("lines", "shippingAddress.country")));
verifyNoInteractions(orders); // the controller method never ran
}
}The errors assertion relies on the advice from Step 3, which @WebMvcTest picks up automatically. The verifyNoInteractions line proves validation stopped the request before any business code.
@Valid versus @Validated, custom constraints and groups
What is the difference between @Valid and @Validated? @Valid is the Jakarta standard and triggers cascading. Spring’s @Validated additionally supports validation groups and, on a class, enables method validation for Spring beans.
How do you write a custom constraint? Create an annotation with @Constraint(validatedBy = MyValidator.class) and implement ConstraintValidator<MyAnnotation, T>. Keep it pure: no database calls.
How do you validate the same DTO differently for create and update? Use validation groups with @Validated(OnCreate.class), or better, separate DTOs per operation. See validation groups.
How do you validate service method arguments? Annotate the service class with @Validated and its parameters with constraints; Spring applies method validation through a proxy.
Practice: validating a password change endpoint
Design validation for PUT /users/{id}/password with a body containing currentPassword and newPassword. The new password must be 12 to 128 characters and differ from the current one, and the current one must be correct.
How to answer
Validate {id} with @Positive on the path variable. On the DTO, use @NotBlank on currentPassword and @NotBlank @Size(min = 12, max = 128) on newPassword. “Must differ” compares two fields, which a class-level custom constraint (for example @PasswordsDiffer) can check without any external state, so it can live in validation. “Current password is correct” requires the stored hash, so it belongs in the service, which throws a domain exception mapped to 400 or 403 with a deliberately vague message. Never echo password values in error messages or logs. The reasoning: structural and self-contained rules go in constraints; anything that needs stored data goes in the service.