Validation
Validation is a critical part of building reliable and secure REST APIs. It ensures that the data sent by the client is correct, complete, and safe before the application processes or stores it.
Without proper validation, invalid or malformed input can cause runtime errors, corrupt the database, or expose security vulnerabilities.
What is Validation?
Validation is the process of verifying that incoming client data meets predefined rules before it is processed by the server.
Validation helps to:
- Ensure data correctness
- Prevent invalid or malicious input
- Avoid runtime errors
- Protect database and business logic
- Improve API reliability and stability
Simple Examples:
- Email must be valid
- Name must not be blank
- Age must be positive
How Validation Works in Spring Boot
Spring Boot provides built-in validation support using Bean Validation (JSR 380), typically implemented via Hibernate Validator.
Validation Flow
ClientJSON
↓
@RequestBody
↓
@Valid
↓
BeanValidationAnnotations
↓
✔ControllerLogic
❌400BadRequest
How it works internally:
- Validation rules are defined using annotations on DTO or model fields
@Validtriggers validation in the controller- If validation fails, Spring automatically returns 400 Bad Request
- No manual
if-elsechecks are required
Common Validation Annotations
| Annotation | Description |
|---|---|
@NotNull | Field must not be null |
@NotBlank | String must not be null, empty, or whitespace |
@Size(min, max) | Length constraints |
@Email | Valid email format |
@Min(value) | Minimum numeric value |
@Max(value) | Maximum numeric value |
@Positive | Must be a positive number |
@Pattern(regex) | Must match a regex |
@Past / @Future | Date validation |
Practical Example: User Registration API
We are creating a User Registration API.
The client sends user details, and the server must validate the input before saving.
User DTO with Validation Rules
publicclassUserDTO {
@NotBlank(message = "Name is required")
private String name;
@Email(message = "Invalid email address")
private String email;
@Min(value = 18, message = "Age must be at least 18")
privateint age;
// getters and setters
}
What happens here?
@NotBlank→ Name cannot be empty@Email→ Email format must be valid@Min(18)→ Age must be 18 or above
Controller Using @Valid
@RestController
@RequestMapping("/users")
publicclassUserController {
@PostMapping("/register")
public ResponseEntity<String>registerUser(
@Valid@RequestBody UserDTO userDTO) {
// Executes only if validation passes
return ResponseEntity
.status(201)
.body("User registered successfully");
}
}
What happens here?
@RequestBody→ Converts JSON into Java object@Valid→ Applies validation rules- Validation success → Controller executes
- Validation failure → 400 Bad Request
Valid Request (Success Case)
{
"name":"Alice",
"email":"[email protected]",
"age":25
}
Response
HTTP/1.1201 Created
User registered successfully
The request data satisfies all validation rules, so the controller method executes successfully.
Invalid Request (Failure Case)
{
"name":"",
"email":"alice.com",
"age":10
}
Automatic Error Response (400 Bad Request)
{
"timestamp":"2026-01-01T12:00:00",
"status":400,
"errors":[
"Name is required",
"Invalid email address",
"Age must be at least 18"
]
}
What Spring Boot Does Automatically
- Detects invalid request data
- Applies validation rules using
@Valid - Stops controller execution
- Returns 400 Bad Request with validation error messages
Handling Validation Errors (Advanced)
For better control and standardized error responses, you can use:
@ControllerAdvice@ExceptionHandler(MethodArgumentNotValidException.class)- Custom error response objects
This improves API usability and developer experience, especially in large applications.
Best Practices
- Always validate client input
- Use DTOs, not entities, for validation
- Combine
@Validwith@RequestBody - Use
ResponseEntityfor proper HTTP status codes - Provide clear and meaningful error messages
- Never rely only on client-side validation
Conclusion
Validation in Spring Boot REST APIs ensures that your application receives clean, safe, and predictable data.
By using Bean Validation annotations with @Valid, Spring Boot automatically handles input validation and error responses, making your APIs robust, secure, and production-ready.
