@Valid Annotation in Spring: What It Is and How It Works
@Valid annotation in Spring is used to trigger validation on an object, usually a request body or form input, based on constraints defined in the object's class. It works with Java Bean Validation API to check if the data meets rules like not being empty or having a valid format before processing.How It Works
The @Valid annotation acts like a checkpoint that tells Spring to check if the data coming into your application follows certain rules. Imagine you are filling out a form and the system automatically checks if you entered a valid email or if a required field is not left blank. This is what @Valid does behind the scenes.
When you add @Valid before an object in a controller method, Spring looks at the rules defined in that object's class using annotations like @NotNull or @Size. If the data breaks any rule, Spring stops and returns an error instead of continuing with wrong data.
Example
This example shows how to use @Valid to check user input in a Spring controller.
import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; 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.RestController; @RestController public class UserController { public static class User { @NotBlank(message = "Name must not be blank") private String name; @Size(min = 5, message = "Password must be at least 5 characters") private String password; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } @PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User is valid: " + user.getName()); } }
When to Use
Use @Valid whenever you want to make sure the data your application receives is correct and safe before using it. This is especially important for data coming from users, like form submissions or API requests.
For example, when creating a new user account, you want to check that the username is not empty and the password is strong enough. Using @Valid helps catch mistakes early and improves your app's reliability and security.
Key Points
- @Valid triggers validation on objects based on their constraint annotations.
- Works with Java Bean Validation API (JSR 380) and implementations like Hibernate Validator.
- Commonly used in Spring MVC controllers on request bodies or form objects.
- Validation errors automatically result in HTTP 400 responses with error details.
- Helps keep data clean and prevents processing invalid input.
Key Takeaways
@Valid ensures input data meets defined rules before processing.@NotBlank and @Size on object fields.