What is Validation in Spring Boot?
Validation in Spring Boot is the process of checking whether incoming data is correct, complete, secure, and follows predefined business rules before processing it.
It helps ensure that applications receive valid user input and prevents invalid, incomplete, or malicious data from entering the system.
In simple words, validation is used to verify user input before saving, updating, or processing data in a Spring Boot application.
Why Validation is Important in Spring Boot
Users can send invalid data intentionally or unintentionally.
Examples:
- Empty username
- Invalid email address
- Weak password
- Negative price value
- Incorrect mobile number
- Null required fields
Without validation:
- Invalid data may enter the database
- Applications may crash unexpectedly
- Security vulnerabilities may occur
- Business rules may fail
- User experience becomes poor
Validation helps maintain:
- Data integrity
- Application security
- Database consistency
- Business rule enforcement
- Reliable API responses
Types of Validation in Spring Boot
| Validation Type | Description |
|---|---|
| Client-Side Validation | Validation performed in browser using JavaScript or HTML |
| Server-Side Validation | Validation performed in Spring Boot backend |
Why Server-Side Validation is Mandatory
Client-side validation can be bypassed easily using tools like Postman, API clients, or browser developer tools.
Therefore, Spring Boot applications must always implement server-side validation.
Validation Framework Used in Spring Boot
Spring Boot mainly uses:
- Bean Validation API
- Hibernate Validator
- Jakarta Validation annotations
Validation Dependency
Spring Boot validation support is usually added using:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Main Validation Annotations in Spring Boot
| Annotation | Purpose |
|---|---|
| @NotNull | Field cannot be null |
| @NotEmpty | Field cannot be null or empty |
| @NotBlank | Field cannot contain only spaces |
| @Size | Defines minimum and maximum length |
| Validates email format | |
| @Min | Minimum numeric value |
| @Max | Maximum numeric value |
| @Pattern | Regex pattern validation |
| @Positive | Value must be positive |
| @Past | Date must be in past |
| @Future | Date must be in future |
Simple Validation Example
Step 1: Create DTO Class
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserRequest {
@NotBlank(message = "Name is required")
private String name;
@Email(message = "Invalid email format")
private String email;
@Size(
min = 6,
max = 12,
message = "Password must be between 6 and 12 characters"
)
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Step 2: Use @Valid in Controller
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String createUser(
@Valid @RequestBody UserRequest request) {
return "User Created Successfully";
}
}
Invalid Request Example
{
"name": "",
"email": "abc",
"password": "12"
}
Validation Error Response
{
"timestamp": "2026-05-18T20:30:00",
"status": 400,
"errors": [
"Name is required",
"Invalid email format",
"Password must be between 6 and 12 characters"
]
}
How Validation Works Internally
When a request reaches the controller:
- Spring Boot reads incoming request data
- @Valid triggers validation process
- Hibernate Validator checks validation annotations
- If validation fails, exception is thrown
- Error response is returned to client
What is @Valid Annotation?
@Valid tells Spring Boot to validate the object before processing it.
Package
import jakarta.validation.Valid;
Difference Between @Valid and @Validated
| Feature | @Valid | @Validated |
|---|---|---|
| Validation Type | Basic validation | Advanced validation |
| Validation Groups | No | Yes |
| Common Usage | DTO validation | Service-level validation |
Handling Validation Exceptions Globally
Validation errors are commonly handled using global exception handling.
Example
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(
MethodArgumentNotValidException.class
)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public List<String> handleValidationException(
MethodArgumentNotValidException ex) {
List<String> errors = new ArrayList<>();
ex.getBindingResult()
.getFieldErrors()
.forEach(error ->
errors.add(error.getDefaultMessage()));
return errors;
}
}
Output
[
"Name is required",
"Invalid email format"
]
Real-Time Example in E-Commerce Application
Suppose an e-commerce application allows users to add products.
Product Request DTO
public class ProductRequest {
@NotBlank(message = "Product name is required")
private String name;
@Positive(message = "Price must be positive")
private double price;
@Min(
value = 1,
message = "Quantity must be at least 1"
)
private int quantity;
}
Controller
@PostMapping("/products")
public String addProduct(
@Valid @RequestBody ProductRequest request) {
return "Product Added Successfully";
}
Advantages of Validation in Spring Boot
- Improves application security
- Prevents invalid database entries
- Enhances user experience
- Maintains data integrity
- Supports clean API design
- Reduces application errors
- Supports enterprise-level applications
Disadvantages of Validation
- Improper validation may affect performance
- Too many validations may increase complexity
- Custom validations require additional coding
Custom Validation in Spring Boot
Spring Boot also supports custom validation annotations.
Example use cases:
- Password strength validation
- Custom business rules
- Age verification
- Company-specific formats
Example of @Pattern Validation
@Pattern(
regexp = "^[0-9]{10}$",
message = "Mobile number must contain 10 digits"
)
private String mobile;
Validation in Microservices
Validation plays a major role in microservices architecture because:
- Services receive external API requests
- Data consistency is critical
- Security validation is important
- Invalid payloads must be rejected early
Common Validation Exceptions
| Exception | Description |
|---|---|
| MethodArgumentNotValidException | Request body validation failure |
| ConstraintViolationException | Parameter validation failure |
| BindException | Binding and validation failure |
Best Practices for Validation in Spring Boot
- Always validate user input
- Use DTO classes instead of entities
- Use meaningful validation messages
- Handle validation errors globally
- Do not expose sensitive validation details
- Use custom validation for business rules
- Combine client-side and server-side validation
Common Interview Questions on Validation
What is validation in Spring Boot?
Validation is the process of verifying user input before processing or saving data.
Why is validation important?
Validation ensures data integrity, security, and proper business rule enforcement.
What is @Valid annotation?
@Valid triggers validation for request objects in Spring Boot.
What is the difference between @NotNull and @NotBlank?
@NotNull checks only null values, while @NotBlank also checks empty and whitespace-only strings.
What exception occurs when validation fails?
MethodArgumentNotValidException usually occurs for request body validation failures.
Difference Between @NotNull, @NotEmpty, and @NotBlank
| Annotation | Allows Null | Allows Empty | Allows Spaces |
|---|---|---|---|
| @NotNull | No | Yes | Yes |
| @NotEmpty | No | No | Yes |
| @NotBlank | No | No | No |
Conclusion
Validation is one of the most important features in Spring Boot applications. It ensures that only correct and secure data enters the system.
Spring Boot provides powerful validation support using Bean Validation, Hibernate Validator, and annotations like @NotBlank, @Email, and @Size.
Proper validation improves application security, reliability, maintainability, and user experience.
Understanding validation is essential for Spring Boot developers because validation is widely used in enterprise applications, REST APIs, microservices, and production-grade backend systems.