Here's a step-by-step explanation of Java Spring validation using the Bean Validation framework:
spring-boot-starter-validation
dependency, which automatically adds the required validation libraries.<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
javax.validation.constraints
package. Common annotations include @NotNull
, @NotEmpty
, @Size
, @Min
, @Max
, etc.public class User {
@NotNull
@Size(min = 5, max = 30, message = "The length of the customer name should be between 5 and 30")
private String name;
@NotEmpty
@Email
private String email;
// other fields and methods...
}
@Valid
annotation to indicate that the input should be validated. This annotation can be applied to method parameters or request body objects.@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
// handle the valid user data
}