Spring Boot REST API Validation Explained (@Valid, All Annotations)

Spring Boot REST API Validation – Complete Guide (All Annotations)

Validation is a core responsibility of any REST API. Spring Boot provides powerful validation support using Bean Validation, but most articles explain only 2–3 annotations. This guide covers ALL commonly used validation annotations, with best practices and interview insights.

You will learn:
  • How validation works internally in Spring Boot
  • All important validation annotations with examples
  • DTO-based validation best practices
  • How to return clean validation error responses
  • Common fresher mistakes interviewers catch

1️⃣ How Validation Works in Spring Boot

Spring Boot uses Bean Validation (JSR 380), with Hibernate Validator as the default implementation.

Client Request
   ↓
@RestController
   ↓
@Valid triggers validation
   ↓
Validation fails → Exception
   ↓
@RestControllerAdvice
   ↓
Error Response
Important: Validation happens BEFORE controller logic executes.

2️⃣ Required Dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Spring Boot 3+ requires explicit validation dependency.

3️⃣ Always Use DTOs for Validation

Never validate directly on JPA entities. Use Request DTOs.

public class UserRequest {

  @NotBlank
  private String name;

  @Email
  private String email;

  @Min(18)
  private Integer age;
}

Why DTOs?

  • API contract control
  • No DB leakage
  • Better versioning

Related: Spring Boot + JPA Basics for Freshers


4️⃣ Core Validation Annotations (Most Used)

AnnotationUsed For
@NotNullValue must not be null
@NotEmptyNot null and not empty (String, Collection)
@NotBlankNot null, not empty, trimmed length > 0 (String)
@SizeMin/max length for String/Collection
Interview tip: @NotBlank works only for String, not numbers.

5️⃣ Numeric Validation Annotations

AnnotationDescription
@MinMinimum numeric value
@MaxMaximum numeric value
@PositiveValue must be > 0
@PositiveOrZeroValue ≥ 0
@NegativeValue < 0
@NegativeOrZeroValue ≤ 0

6️⃣ String Pattern & Format Validation

AnnotationUse Case
@EmailEmail format
@PatternRegex validation
@Pattern(
  regexp = "^[0-9]{10}$",
  message = "Mobile number must be 10 digits"
)
private String mobile;

7️⃣ Date & Time Validation

AnnotationPurpose
@PastDate must be in the past
@PastOrPresentPast or present
@FutureDate must be in the future
@FutureOrPresentFuture or present

8️⃣ Using @Valid in Controller

@PostMapping("/users")
public String createUser(
    @Valid @RequestBody UserRequest request) {
  return "User created";
}

If validation fails:

  • Method is NOT executed
  • Exception is thrown automatically

Related: Spring Boot Annotations Explained


9️⃣ Validating Path Variables & Request Params

@GetMapping("/{id}")
public String getUser(
    @PathVariable @Min(1) Long id) {
  return "User ID " + id;
}
@Valid is mainly for @RequestBody. Path params need direct constraints.

๐Ÿ”Ÿ Handling Validation Errors Cleanly

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(MethodArgumentNotValidException.class)
  public Map<String, String> handleValidation(
      MethodArgumentNotValidException ex) {

    Map<String, String> errors = new HashMap<>();

    ex.getBindingResult().getFieldErrors()
      .forEach(error ->
        errors.put(error.getField(), error.getDefaultMessage())
      );

    return errors;
  }
}

Learn error handling in depth: Global Exception Handling in Spring Boot


11️⃣ Common Fresher Mistakes (Interview Gold)

  • Forgetting @Valid in controller
  • Validating JPA entities directly
  • Not handling validation errors globally
  • Using wrong annotation (@NotNull vs @NotBlank)
Interview-ready line: “I use DTOs + Bean Validation + global exception handling.”

Final Summary

  • Validation protects APIs from bad input
  • @Valid triggers Bean Validation
  • DTO-based validation is best practice
  • Clean errors improve API quality

Mastering validation makes you look like a production-ready Spring Boot fresher.


๐Ÿงพ Master Validation in Spring Boot REST APIs

Proper validation is essential for building safe, reliable, and production-ready REST APIs. Strengthen your Spring Boot knowledge by exploring these closely related validation and REST topics.

✅ Custom Validation Annotations in Spring Boot

Learn how to create reusable custom validators when built-in annotations are not enough.

๐Ÿšจ Spring Boot Global Exception Handling

Handle validation errors consistently using @ControllerAdvice.

๐Ÿท️ Spring Boot Annotations for REST APIs

Understand commonly used Spring annotations for building clean REST controllers.

๐ŸŽฏ Controller vs RestController

Learn the difference between MVC and REST controllers and how validation fits in.

๐ŸŽ“ Spring Boot Interview Questions (Freshers)

Common interview questions covering validation, REST APIs, and Spring Boot basics.

๐Ÿ’ผ Spring Boot Interview Questions (2–5 Years)

Interview topics including validation strategies, error handling, and REST best practices.