0
0
Spring Bootframework~5 mins

@Valid annotation on request body in Spring Boot

Choose your learning style9 modes available
Introduction

The @Valid annotation checks if the data sent to your app is correct before using it. It helps catch mistakes early.

When you want to make sure user input in a form is complete and correct.
When receiving data from an API client and you need to check it follows rules.
When saving data to a database and want to avoid bad or missing values.
When you want to give clear error messages if input is wrong.
When you want to keep your app safe from invalid or harmful data.
Syntax
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.

Examples
Validates the UserDto object sent in the request body before processing.
Spring Boot
@PostMapping("/user")
public ResponseEntity<?> createUser(@Valid @RequestBody UserDto user) {
    // save user
}
Example of a data class with validation rules: name cannot be blank, quantity must be positive.
Spring Boot
public record ProductDto(@NotBlank String name, @Positive int quantity) {}
Validates the product data sent in the request body using the rules in ProductDto.
Spring Boot
@PostMapping("/product")
public ResponseEntity<?> addProduct(@Valid @RequestBody ProductDto product) {
    // add product
}
Sample Program

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.

Spring Boot
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.");
    }
}
OutputSuccess
Important Notes

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.

Summary

@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.