Bean Validation
Bean Validation (JSR 380) provides a standard way to validate data using annotations.
Basic Validation Annotations
public class CreateUserRequest {
@NotBlank(message = "Name is required")
@Size(min = 2, max = 100, message = "Name must be 2-100 characters")
private String name;
@NotBlank(message = "Email is required")
@Email(message = "Email must be valid")
private String email;
@NotNull(message = "Age is required")
@Min(value = 18, message = "Must be at least 18")
@Max(value = 120, message = "Must be at most 120")
private Integer age;
@NotBlank(message = "Password is required")
@Size(min = 8, message = "Password must be at least 8 characters")
@Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).*$",
message = "Password must contain uppercase, lowercase, and digit")
private String password;
}
Common Annotations
| Annotation | Validates |
|---|---|
@NotNull |
Not null |
@NotBlank |
Not null and not empty string |
@NotEmpty |
Not null and not empty collection/string |
@Size(min, max) |
String/collection length |
@Min(value) |
Minimum numeric value |
@Max(value) |
Maximum numeric value |
@Email |
Valid email format |
@Pattern(regex) |
Matches regex pattern |
@Positive |
Must be positive |
@PositiveOrZero |
Must be >= 0 |
@Past |
Must be in the past |
@Future |
Must be in the future |
Enabling Validation
@RestController
@RequestMapping("/api/users")
public class UserController {
// @Valid triggers validation
@PostMapping
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserRequest request) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(userService.createUser(request));
}
}
Validation Best Practices
Validation Layers
- Client-side: Immediate feedback
- API Gateway: Basic validation
- Service: Business rules
- Database: Constraints
Types
- Type checking
- Format validation (email, phone)
- Range checking
- Length limits
- Business rules
Best Practices
- Validate on server (never trust client)
- Return specific error messages
- Use whitelist approach
- Log validation failures
Key Points
- Understanding Validation is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Validation in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Validation implementation
// Key aspects: validation, error handling, logging, testing
public class Validation {
// Production-ready implementation
}Identify and handle edge cases for Validation. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Validation. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. What is the difference between @NotNull and @NotBlank?
2. How do you trigger validation on a request body in a controller?
3. What is the primary purpose of Validation?
4. What is a common mistake when implementing Validation?
Flashcards
Question
What does @Valid do?
Click to reveal answer
Answer
Triggers Bean Validation on the annotated parameter
Question
Difference between @NotNull and @NotBlank?
Click to reveal answer
Answer
@NotNull = not null. @NotBlank = not null + not empty + not whitespace
Question
What is Validation?
Click to reveal answer
Answer
Validation is a key concept in backend development.
Question
When to use Validation?
Click to reveal answer
Answer
Use Validation when building production systems that require reliability, scalability, and maintainability.
Question
Validation best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.@Valid triggers Bean Validation on request objects in controllers
- 2.@NotNull checks for null, @NotBlank checks for null, empty, and whitespace-only strings
- 3.Use @Size for string/collection length, @Min/@Max for numeric ranges
- 4.@Email validates email format, @Pattern allows custom regex validation
- 5.Validation errors throw MethodArgumentNotValidException, handle in global exception handler
Interview Tips
- •Explain the difference between @NotNull, @NotBlank, and @NotEmpty with examples
- •Know common validation annotations and when to use each one
- •Discuss how to create custom validators using @Constraint annotation
Cheat Sheet
Bean Validation
- @Valid: triggers validation on request objects
- @NotNull: not null
- @NotBlank: not null + not empty + not whitespace
- @NotEmpty: not null + not empty string/collection
- @Size(min, max): string/collection length
- @Min(value), @Max(value): numeric range
- @Email: valid email format
- @Pattern(regex): custom regex validation
- Errors thrown as MethodArgumentNotValidException