Spring Boot Validation
Spring Boot provides a way to validate data in your applications using the Java Bean Validation API (JSR 380) along with Hibernate Validator as the default implementation.
1. Adding Dependencies
To use validation in Spring Boot, add the following dependency in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2. Using Validation Annotations
You can use annotations on your model or DTO fields:
@NotNull- Field cannot be null@NotEmpty- Field cannot be empty@NotBlank- Field cannot be blank@Size(min=, max=)- Field must have specified size@Email- Field must be a valid email@Pattern(regexp="")- Field must match a regex pattern
3. Example Model with Validation
public class User {
@NotNull(message = "Name cannot be null")
@Size(min = 2, max = 30, message = "Name must be between 2 and 30 characters")
private String name;
@Email(message = "Email should be valid")
private String email;
@NotNull(message = "Age cannot be null")
private Integer age;
// Getters and Setters
}
4. Validating in Controller
Use @Valid and BindingResult to handle validation in controllers:
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping("/add")
public String addUser(@Valid @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
return result.getAllErrors().toString();
}
return "User is valid";
}
}
5. Custom Validation
You can create custom validators by implementing ConstraintValidator:
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
public @interface CustomConstraint {
String message() default "Invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class CustomValidator implements ConstraintValidator<CustomConstraint, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && value.startsWith("A");
}
}
6. Summary
Spring Boot Validation helps in ensuring data integrity and reducing errors by validating inputs at the API level. Using annotations and custom validators makes it easy to implement robust validation logic in your applications.
Was this tutorial helpful?