Spring Boot Validation Tutorial with Real Examples

Spring Boot Validation Tutorial with Real Examples

Validation Tutorial

Introduction

Data validation is an essential part of every application. Without proper validation, users can submit invalid, incomplete, or malicious data that may cause application errors and database inconsistencies.

Spring Boot provides built-in validation support using Jakarta Bean Validation. By applying validation annotations, developers can ensure that incoming data meets specific requirements before processing it.

In this tutorial, you'll learn how to validate request data in Spring Boot using practical examples.


What is Validation?

Validation is the process of checking whether input data satisfies predefined rules.

Examples:

✅ Name should not be empty

✅ Email should be valid

✅ Password should have a minimum length

✅ Age should be positive

Without validation:

{
  "name":"",
  "email":"abc",
  "age":-10
}

This data should not be accepted by the application.


Why Validation is Important

Validation helps:

  • Improve data quality
  • Prevent invalid database records
  • Improve API reliability
  • Improve user experience
  • Enhance security

Add Validation Dependency

Add the following dependency to your pom.xml:

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

This dependency enables Jakarta Bean Validation support.


Create EmployeeDTO

Validation should usually be applied to DTO classes.

public class EmployeeDTO {

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

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

    @NotBlank(message =
        "Department is required")
    private String department;

}

Understanding Validation Annotations

@NotBlank

Used for String values.

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

Rejects:

null
""
"   "

@NotNull

Used when a field cannot be null.

@NotNull
private Long employeeId;

@Email

Validates email addresses.

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

Valid:

john@example.com

Invalid:

john
john@

@Size

Controls minimum and maximum length.

@Size(
   min = 3,
   max = 50,
   message =
   "Name must be between 3 and 50 characters")
private String name;

@Min

Minimum numeric value.

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

@Max

Maximum numeric value.

@Max(
   value = 60,
   message =
   "Age cannot exceed 60")
private int age;

Enable Validation in Controller

Use @Valid before the request body.

@PostMapping
public Employee createEmployee(

      @Valid
      @RequestBody EmployeeDTO employeeDTO) {

      return service.save(employeeDTO);
}

When invalid data is submitted, Spring automatically triggers validation.


Valid Request Example

{
   "name":"Muhammad Zeeshan",
   "email":"zeeshan@example.com",
   "department":"IT"
}

Invalid Request Example

{
   "name":"",
   "email":"invalid",
   "department":""
}

Validation Error Response

{
   "timestamp":"2026-07-24",
   "status":400,
   "errors":[
      "Name is required",
      "Invalid email format",
      "Department is required"
   ]
}

Global Validation Exception Handling

Create:

GlobalExceptionHandler.java

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(
      MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String,String>>
        handleValidationExceptions(

        MethodArgumentNotValidException ex) {

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

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

        return ResponseEntity
               .badRequest()
               .body(errors);
    }
}

Sample Validation Response

{
   "name":"Name is required",
   "email":"Invalid email format"
}

This makes API responses much cleaner and easier to understand.


Custom Validation Example

Sometimes built-in annotations are not enough.

Example:

Company emails only.

Allowed:
john@company.com

Rejected:
john@gmail.com

This can be implemented using a custom validator.


Validation Flow Diagram

Client Request
      ↓
Controller
      ↓
@Valid
      ↓
Validation Rules
      ↓
Valid Data?
   ↙      ↘
 Yes       No
 ↓          ↓
Service   Error Response
 ↓
Database

Best Practices

Validate DTOs

Avoid validating Entity classes directly.

Use Meaningful Messages

Good:

@NotBlank(
 message="Name is required")

Bad:

@NotBlank

Centralize Exception Handling

Use:

@RestControllerAdvice

Keep Validation Close to Input

Validate requests before business logic executes.


Common Mistakes

Forgetting @Valid

Without:

@Valid

Validation will not execute.


Using Validation on Entity Only

Prefer DTO validation.


Ignoring Error Responses

Always return meaningful validation messages.


Interview Questions

What is Bean Validation?

Bean Validation is a specification used to validate Java objects using annotations.


What is @Valid?

@Valid triggers validation before processing a request.


Difference Between @NotNull and @NotBlank?

@NotNull:

Rejects null

@NotBlank:

Rejects null
Rejects ""
Rejects whitespace

What is MethodArgumentNotValidException?

It is thrown when request validation fails.


FAQ

Does Spring Boot support validation out of the box?

Yes, after adding the validation dependency.

Can validation be applied to REST APIs?

Yes, it is commonly used in REST APIs.

Can I create custom validation annotations?

Yes.

Should validation be done in DTOs or Entities?

DTOs are generally recommended.

 

Continue Learning Spring Boot

Muhammad Zeeshan Haider

Hello, I'm Muhammad Zeeshan, a Java Developer, Spring Boot Educator, and Technical Blogger. Through Java Web Action, I share practical tutorials, guides, and real-world examples on Java, Spring Boot, Microservices, REST APIs, JPA, Hibernate, MySQL, and software architecture. My goal is to help developers learn modern Java technologies and build professional applications with confidence.

Post a Comment

Please enter relevant questions and information.

Previous Post Next Post