Validation in Spring Boot using Jakarta Bean Validation

Data validation is a key part of building robust APIs. Spring Boot integrates with Jakarta Bean Validation (formerly JSR 380, previously known as Hibernate Validator) to provide a powerful and declarative validation mechanism.

This post will walk you through how to use @Valid along with validation annotations to ensure your incoming data meets the expected constraints.

Validation in Spring Boot using Jakarta Bean Validation

โœ… Basic Setup

Step 1: Add Spring Web and Validation Dependencies

If you’re using Maven, just add spring-boot-starter-web. It already includes validation dependencies.

๐Ÿงฑ Example: Validating a User Registration Request

๐Ÿ“ Model: User.java

๐Ÿ“‚ Controller: UserController.java

๐Ÿ”ฅ What happens if the input is invalid?

Spring will automatically return a 400 Bad Request with a descriptive error message like:

๐Ÿ“ค Sample JSON Input

โœ… Valid Input

โŒ Invalid Input

๐Ÿงฐ Common Jakarta Validation Annotations

AnnotationDescription
@NotNullField must not be null
@NotBlankNot null and trimmed length > 0
@Size(min, max)Checks size of string, list, etc.
@Min, @MaxChecks numerical values
@EmailValidates email format
@Pattern(regexp = "")Validates against regex
@Positive, @NegativeChecks for positive/negative numbers

๐ŸŽฏ Custom Error Handling with @ControllerAdvice

๐Ÿ“ Create GlobalExceptionHandler.java

๐Ÿ” Sample Error Response

๐Ÿš€ Validating Nested Objects

Use @Valid on nested fields as well to trigger recursive validation.

โœ๏ธ Custom Validation Annotation (Advanced)

Step 1: Define Annotation

Step 2: Implement the Validator

Use it in your model:

๐Ÿงช Testing with curl

Expected response:

๐Ÿงพ External References