Spring Boot

Article 10: Request Validation in Spring Boot

By Utility Zone · 2026-01-27T18:29:30.828701

1. Introduction

APIs should never trust input.

Without validation:

  • Invalid data enters the system
  • Databases get corrupted
  • Bugs appear far away from the source

Spring Boot provides Bean Validation to validate requests cleanly and declaratively.


2. What Is Bean Validation?

Bean Validation:

  • Uses annotations to define constraints
  • Automatically validates request bodies
  • Returns meaningful error responses

Spring Boot integrates Bean Validation seamlessly.


3. Adding Validation Dependency

If you are using spring-boot-starter-web, validation is usually included. If not, add:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

4. Validating Request Body with @Valid

4.1 Update Entity / DTO

package com.example.demo.dto;

import jakarta.validation.constraints.*;

public class UserRequest {

    @NotBlank(message = "Name is mandatory")
    private String name;

    @Email(message = "Email should be valid")
    @NotBlank(message = "Email is mandatory")
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;

    // getters and setters
}

4.2 Use @Valid in Controller

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

Spring automatically:

  • Validates request
  • Stops execution if validation fails

5. Common Validation Annotations

AnnotationPurpose
@NotNullValue must not be null
@NotBlankNon-empty string
@SizeLength constraint
@EmailEmail format
@Min, @MaxNumeric limits

6. Validation Error Response (Default)

If validation fails, Spring returns:

  • HTTP 400 (Bad Request)
  • Field-specific error messages

Example:

{
  "errors": [
    "Email should be valid",
    "Name is mandatory"
  ]
}

(Default format may vary)


7. Validating Path Variables and Request Params

@GetMapping("/users/{id}")
public User getUser(@PathVariable @Min(1) Long id) {
    return userService.getUser(id);
}

Enable method validation:

@Validated
@RestController
public class UserController {
}

8. Custom Validation Messages

Add to application.properties:

spring.messages.basename=messages

Create:

messages.properties
NotBlank.userRequest.name=Name cannot be empty

9. Common Beginner Mistakes

❌ Forgetting @Valid
❌ Validating entity instead of DTO
❌ No error handling strategy
❌ Ignoring validation errors

✔ Always validate at API boundary


10. Best Practices

✔ Use DTOs for validation
✔ Keep entities clean
✔ Fail fast on invalid input
✔ Provide meaningful error messages


11. What You Should Understand Before Moving On

You should now know:

  • Why validation matters
  • How @Valid works
  • Common validation annotations
  • How Spring handles validation errors

12. What’s Next?

➡ Article 11: Exception Handling the Right Way

  • @ExceptionHandler
  • @ControllerAdvice
  • Standard error responses

Type Next when you’re ready.