The @Valid annotation checks if the data sent to your app is correct before using it. It helps catch mistakes early.
@Valid annotation on request body in Spring Boot
@PostMapping("/example")
public ResponseEntity<?> exampleMethod(@Valid @RequestBody ExampleDto dto) {
// method body
}The @Valid annotation is placed before the @RequestBody parameter.
The class of the request body (like ExampleDto) must have validation annotations on its fields.
UserDto object sent in the request body before processing.@PostMapping("/user")
public ResponseEntity<?> createUser(@Valid @RequestBody UserDto user) {
// save user
}public record ProductDto(@NotBlank String name, @Positive int quantity) {}ProductDto.@PostMapping("/product")
public ResponseEntity<?> addProduct(@Valid @RequestBody ProductDto product) {
// add product
}This Spring Boot controller has a POST endpoint /api/users. It expects a JSON body matching UserDto with rules: name not blank, email valid, age at least 18. If validation passes, it returns a success message.
import jakarta.validation.Valid; import jakarta.validation.constraints.*; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api") public class SampleController { public record UserDto( @NotBlank(message = "Name is required") String name, @Email(message = "Email must be valid") String email, @Min(value = 18, message = "Age must be at least 18") int age ) {} @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody UserDto user) { return ResponseEntity.ok("User " + user.name() + " created successfully."); } }
Validation errors automatically return a 400 Bad Request with error details if you have Spring Boot's default error handling.
Use annotations like @NotBlank, @Email, @Min on fields inside your DTO class to define rules.
Make sure to include spring-boot-starter-validation dependency in your project to enable validation.
@Valid checks request body data before your method uses it.
Put @Valid before @RequestBody parameter in controller methods.
Define rules inside the data class with validation annotations.