Sub topic 4
Triggering validation with @Valid
This chapter assumes you have a Spring Boot REST controller that accepts JSON, and that spring-boot-starter-validation is on the classpath. It also assumes your request DTO already carries constraint annotations such as @NotBlank and @Min. Here you will learn what turns those annotations into actual checks, when the checks run, and what you see when they fail.
Annotations alone do nothing
A constraint annotation is only a declaration. Writing @NotBlank on a record component does not make anything happen when the record is created. Java will happily build new CreateUserRequest("", "nope", 3).
Validation runs only when something asks a Validator to check the object. In a Spring MVC controller, that something is the argument resolver for @RequestBody. It looks at the parameter and checks for an @Valid annotation or an @Validated annotation. If it finds one, it validates the object right after deserialization.
The basic pattern
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) {
}To trigger validation, add @Valid in front of @RequestBody:
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();
}
}The method body runs only if every constraint passes. If any constraint fails, Spring throws an exception and your method is never called. That is the main benefit: the body can assume the data is well-formed and does not need to repeat the checks.
The order of events
Several things happen before your method runs. A failure at each step produces a different exception, so the order matters when you debug.
Two consequences follow:
- Validation never sees a body that failed to parse. A request with
"age": "abc"fails at deserialization, and your@Min(18)is never evaluated. - Constraints run on whatever Jackson produced. A missing JSON field becomes
null, so@NotNullor@NotBlankis what catches it.@Min(18)on its own acceptsnull, because most standard constraints treatnullas valid.
What a failure looks like
Send an invalid body to the controller:
curl -i -X POST http://localhost:8080/users \
-H "Content-Type: application/json" \
-d '{"name":"","email":"nope","age":12}'With no exception handler in your application, Spring Boot responds with status 400 Bad Request and its default error body. With the @RestControllerAdvice that you will write in a later chapter, the body can list one message per field:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"instance": "/users",
"errors": {
"name": "must not be blank",
"email": "must be a well-formed email address",
"age": "must be greater than or equal to 18"
}
}Validation collects all violations in one pass. It does not stop at the first failure. The order of entries in errors is not guaranteed, so clients should not depend on it.
@Valid versus @Validated
Both annotations can trigger validation on a @RequestBody parameter, and in most cases they behave the same. They come from different places and do different jobs:
| Annotation | Package | Can go on | Supports groups | Cascades into nested objects |
|---|---|---|---|---|
| `@Valid` | `jakarta.validation` | Parameters, fields, container elements | No | Yes, when placed on a field |
| `@Validated` | `org.springframework.validation.annotation` | Classes, methods, parameters | Yes | No |
Use @Valid as your default on request bodies. Reach for @Validated in two situations:
- You need validation groups, for example different rules for create and update. A later chapter covers this.
- You put it on the controller class to enable constraints directly on path variables and request parameters, as in the next chapter.
Handling errors yourself with BindingResult
If you declare a BindingResult parameter immediately after the validated parameter, Spring does not throw MethodArgumentNotValidException. Instead it puts the violations in the BindingResult and calls your method, so you decide what to do:
import jakarta.validation.Valid;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LenientUserController {
@PostMapping("/users/lenient")
public ResponseEntity<?> create(@Valid @RequestBody CreateUserRequest request,
BindingResult result) {
if (result.hasErrors()) {
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError error : result.getFieldErrors()) {
errors.putIfAbsent(error.getField(), error.getDefaultMessage());
}
return ResponseEntity.badRequest().body(errors);
}
return ResponseEntity.status(201).build();
}
}This approach works but has a cost. Every endpoint that does it repeats the same handling code, and it is easy to forget the hasErrors() check, which lets invalid data through. For REST APIs, a single central handler is usually the better choice. Use BindingResult only when one endpoint needs different behavior from the rest.
Common errors
Nothing is validated and invalid data gets through. The usual causes are a missing @Valid, or a missing spring-boot-starter-validation dependency. Without the starter, there is no validator implementation. Depending on your Spring Boot version, the failure is either silent or an error about a missing provider.
Annotations on the wrong target. On a record, constraints placed on the components apply to the generated fields and accessors, which is what you want. On a regular class, annotate fields rather than setters, and be consistent so you do not end up with the same rule twice.
A body that is null or absent. If the request has no body, Spring throws HttpMessageNotReadableException before validation, because @RequestBody is required by default. If a JSON body is the literal null, validation is skipped, because there is no object to validate. Do not rely on @Valid to reject a missing body.
Primitive types hide missing fields. If you declare int age, a missing field becomes 0, and @NotNull has nothing to catch. Use wrapper types such as Integer for fields that must be present, as the DTO above does.
Validation inside a service does not run. @Valid on a parameter of an ordinary service method does nothing by itself. Only the controller argument resolver acts on it. A later chapter covers validating beyond the controller.
Form and query binding
@Valid also works on a parameter that is bound from form data or query parameters, the so-called model attribute binding that applies when you omit @RequestBody:
@GetMapping("/users/search")
public String search(@Valid UserSearch search) {
return "ok";
}The binding rules differ from JSON. Spring copies request parameters onto the object, and a type mismatch such as age=abc is recorded as a binding error rather than a parse exception. Violations are reported as a BindException, and MethodArgumentNotValidException is a subclass of it. Handling BindException in your advice covers both cases.
Exercise
A client sends POST /users with the body {"name":"Ana","email":"[email protected]","age":"twenty"} to the controller above. Which exception is thrown, and does the @Min(18) constraint get evaluated?
Show answer
HttpMessageNotReadableException is thrown, because Jackson cannot convert the string "twenty" to an Integer. The @Min(18) constraint is never evaluated, since validation only runs after the DTO has been built successfully.
Exercise
A controller method has the signature create(@Valid @RequestBody CreateUserRequest request, BindingResult result) and does not check result. A client sends an invalid body. What response does the client get, and why is this risky?
Show answer
The method runs normally and likely returns a success status, because the BindingResult parameter suppresses the exception and the violations are only recorded in it. Invalid data then reaches the business logic. This is why a central exception handler, or an explicit result.hasErrors() check, is needed whenever BindingResult is declared.