Skip to content
intermediate Phase · Spring Boot Fundamentals

Validation in Spring

Validate request data using Bean Validation annotations.

40m
0 problems
Topic Progress 0%

Validation Annotations

Common Annotations

public class CreateProductRequest {

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 100)
    private String name;

    @NotNull(message = "Price is required")
    @Positive(message = "Price must be positive")
    private BigDecimal price;

    @Email(message = "Invalid email")
    private String sellerEmail;

    @Pattern(regexp = "^[A-Z]{2}-[0-9]{8}$")
    private String productCode;

    @PastOrPresent
    private LocalDate manufacturingDate;

    @NotEmpty
    private List<String> categories;
}

Annotation Reference

Annotation Validation
@NotNull Not null
@NotBlank Not null, not empty, not whitespace
@NotEmpty Not null, not empty (collections)
@Size String/collection size bounds
@Min/@Max Numeric bounds
@Positive/@Negative Positive/negative numbers
@Email Email format
@Pattern Regex match
@Past/@Future Date in past/future

Custom Validator

@Constraint(validatedBy = UniqueEmailValidator.class)
@Target({FIELD})
@Retention(RUNTIME)
public @interface UniqueEmail {
    String message() default "Email already exists";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class UniqueEmailValidator
        implements ConstraintValidator<UniqueEmail, String> {

    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean isValid(String email, ConstraintValidatorContext context) {
        return email != null && !userRepository.existsByEmail(email);
    }
}

Validation Best Practices

Validation Layers

  1. Client-side: Immediate feedback
  2. API Gateway: Basic validation
  3. Service: Business rules
  4. 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 Spring 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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0 / 3 solved
Implement Spring Validation

Design and implement a solution for Spring Validation in a backend system. Consider scalability, error handling, and production readiness.

Solution
// Spring Validation implementation
// Key aspects: validation, error handling, logging, testing

public class SpringValidation {
    // Production-ready implementation
}
Spring Validation Edge Cases

Identify and handle edge cases for Spring 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, idempotency
Spring Validation Testing Strategy

Write a testing strategy for Spring Validation. Include unit tests, integration tests, and performance tests.

Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injection

Quiz

1. What is the difference between @NotBlank and @NotNull?

Question 1 options

2. Where do you enable validation in a controller?

Question 2 options

3. What is a common mistake when implementing Spring Validation?

Question 3 options

Flashcards

Question

@NotBlank vs @NotNull?

Answer

@NotBlank: not null + not empty + not whitespace. @NotNull: not null only.

Question

How to enable validation in controller?

Answer

@Valid on @RequestBody parameter

Question

Spring Validation best practices

Answer

Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.

Revision Notes

Key Takeaways

  • 1. Use @Valid on @RequestBody to enable validation
  • 2. @NotBlank > @NotNull (rejects empty/whitespace)
  • 3. Create custom validators with @Constraint
  • 4. Return 422 Unprocessable Entity for validation errors

Interview Tips

  • Know validation annotations
  • Implement custom validators

Cheat Sheet

Validation

  • @Valid: Enable on @RequestBody
  • @NotBlank: Not null + not empty + not whitespace
  • @NotNull: Not null only
  • @Size, @Min, @Max: Bounds
  • @Email, @Pattern: Format
  • Custom: @Constraint + Validator class