Spring Boot – Validation using Hibernate Validator
Last Updated :
26 Mar, 2025
Hibernate Validator provides a powerful and flexible way to validate data in Spring Boot applications. Validating user input is essential for building secure and reliable applications. Spring Boot makes this easy with Hibernate Validator, the reference implementation of JSR 380 (Bean Validation API). It allows developers to use rules on user inputs using simple annotations like @NotNull, @Size, and @Email.
In this article, we will explore how to implement validation in Spring Boot, understand common Hibernate Validator annotations, and handle validation errors effectively.
Common Hibernate Validator Annotation
Hibernate validators provide the following annotations that are very helpful for software development.
Annotation
| Usages
|
---|
@NotNull | @NotNull ensures that a field is not null but allows empty values (e.g., an empty string or an empty collection). |
@NotEmpty | @NotEmpty ensures that a field is not null and also not empty, meaning it must contain at least one element (for collections) or at least one character (for strings). |
@NotBlank | @NotBlank applies only to strings and ensures they are not null, not empty, and contain at least one non-whitespace character (i.e., spaces alone are not allowed). |
@Min | Given Minimum value has to be satisfied |
@Max | Given Maximum value has to be satisfied |
@Size | Field size should be less than or greater than the specified field size |
@Email | Email can be validated with this |
@Pattern | Given the RegEx Pattern has to be satisfied. |
Examples of Validator Annotations
Let us start with a bean class GeekEmployee.java below contains examples of validators. In this, we will be using Lombok dependency to generate boilerplate code i.e. for Getter, Setter, etc.
1. @NotNull
Let’s create a field Emp_id. Initially, the first thought that comes to our mind about Employee Id is that it can not be a NULL but can be left Empty in case it is auto-generated i.e. it should be assigned with any number, NULL can not be assigned.
Java
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class GeekEmployee {
@NotNull(message = "Enter a valid Employee Id")
private Long Emp_id;
}
Note: @Data Annotation is used to generate Getter, Setter, etc for the data fields.
2. @NotEmpty
Now create Phone Number field for an Employee. As Phone Number cannot be NULL and also it can not be left Empty.
Java
import lombok.Data;
import jakarta.validation.constraints.NotEmpty;
@Data
public class GeekEmployee {
@NotEmpty(message = "Must not be Empty and NULL")
private String phoneNumber;
}
3. @NotBlank
For field ‘Name’, it can’t be assigned with NULL, must contain some value, not be Blank. Overall it contains @NotEmpty.
Java
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class GeekEmployee {
@NotBlank(message = "employee name can't be left empty")
private String geekEmployeeName;
}
3. @Min and @Max
We can apply these annotations to Age field of Employee. The maximum working age must be 60 and for minimum working age it should be 18.
Java
import lombok.Data;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@Data
public class GeekEmployee {
@Min(value=18, message = "Minimum working age 18")
@Max(value=60, message = "Maximum working age 60")
private Integer age;
}
4. @Email
You can configure Email using regexp and also email must not be NULL.
Java
import lombok.Data;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
@Data
public class GeekEmployee {
@Email(message = "Please enter a valid email Id")
@NotNull(message = "Email cannot be NULL")
private String geekEmailId;
}
Note: You can apply more than one Validator to any field.
5. @Pattern
this annotation provide a powerful tool to customize inputs for any field, it allows us to validate data as per a regexp we can be used to add constraint to any data.
Java
import lombok.Data;
import jakarta.validation.constraints.Pattern;
@Data
public class GeekEmployee {
@Pattern(regexp = "^[0-9]{5}$", message = "Employee postal code must be a 5-digit number.")
private String employeePostalCode;
}
Note: @Pattern can be used to create a custom Email annotation using regexp.
6. @Size
As the name suggests @Size can be used to add a constraint of length to any field.
Java
import lombok.Data;
import jakarta.validation.constraints.Size;
@Data
public class GeekEmployee {
@Size(
min = 10, max = 100,
message= "Address should have a length between 10 and 100 characters.")
private String employeeAddress;
}
Setting Up the Project
Step 1: Folder structure layout

Step 2: Add Dependencies
This is the maven project, add the spring-boot-starter-validation dependency to the pom.xml file. This includes Hibernate Validator as the default implementation of the Bean Validation API.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Step 3: Create an Entity Class
Let’s create an entity class GeekEmployee with validation annotations applied to its fields.
GeekEmployee.java:
Java
import lombok.Data;
import jakarta.validation.constraints.*;
@Data
public class GeekEmployee {
@NotNull(message = "Enter a valid Employee Id")
private Long Emp_id;
@NotEmpty(message = "Must not be Empty and NULL")
private String phoneNumber;
@NotBlank(message = "Employee name can't be left empty")
private String geekEmployeeName;
@Min(value = 18, message = "Minimum working age 18")
@Max(value = 60, message = "Maximum working age 60")
private Integer age;
@Email(message = "Please enter a valid email Id")
private String geekEmailId;
@Pattern(regexp = "^[0-9]{5}$", message = "Employee postal code must be a 5-digit number.")
private String employeePostalCode;
@Size(
min = 10, max = 100,
message = "Address should have a length between 10 and 100 characters.")
private String employeeAddress;
}
Step 4: Exception handling for Validators Errors
When validation fails, Spring Boot throws a MethodArgumentNotValidException. We can handle this exception globally using @ControllerAdvice and return a structured error response.
GlobalExceptionHandler.java:
Java
package com.example.exception;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
// Create a response body map
Map<String, Object> responseBody = new HashMap<>();
responseBody.put("timestamp", Instant.now().toString()); // ISO-8601 timestamp
responseBody.put("status", status.value());
responseBody.put("error", status.getReasonPhrase()); // e.g., "Bad Request"
// Collect all validation errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(fieldError -> fieldError.getDefaultMessage())
.collect(Collectors.toList());
responseBody.put("errors", errors);
return new ResponseEntity<>(responseBody, headers, status);
}
}
Let us try to save the geek employees by accepting the inputs like “geekEmployeeName”, “salary”, “geekEmailId”, and “qualifications”. We need a rest controller file to achieve the same.
Step 5: REST Controller for Validation
Let’s create a REST controller to test the validation.
GeekEmployeeController.java:
Java
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/geekemployees")
public class GeekEmployeeController {
@PostMapping
public ResponseEntity<GeekEmployee> createGeekEmployee(
@Valid @RequestBody GeekEmployee geekEmployee) {
return ResponseEntity
.status(HttpStatus.CREATED)
.body(geekEmployee);
}
}
Note:
- @Valid: This annotation triggers validation on the Employee object.
- Response: If validation passes, the employee object is returned with a 201 CREATED status.
Step 6: Running the Application
Run the Spring Boot application using the following command
mvn spring-boot:run
Note: To run application using IDE goto main method in Spring Boot Application class and run the main method.
On running the application, in the console, we can see as following

Let’s check the working part by using the Postman client as we are using post-mapping

Using the Hibernate validator, front-end validations can be checked and that helps a lot in spring boot projects simply a dependency makes these kinds of validations validate a page.
Similar Reads
Spring Boot - Transaction Management Using @Transactional Annotation
The @Transactional annotation is the metadata used for managing transactions in the Spring Boot application. To configure Spring Transaction, this annotation can be applied at the class level or method level. In an enterprise application, a transaction is a sequence of actions performed by the appli
9 min read
Spring Boot - Map Entity to DTO using ModelMapper
In enterprise applications, we use RESTful services to establish the communication between client and server. The general idea is that the client sends the request to the server and the server responds to that request with some response. Generally, we have three different layers in most of the appli
8 min read
Spring Boot | How to consume JSON messages using Apache Kafka
Apache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer
3 min read
Spring Boot | How to consume string messages using Apache Kafka
Apache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application. Approa
3 min read
Spring Boot | How to publish String messages on Apache Kafka
Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send string messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, r
2 min read
Spring Boot | How to publish JSON messages on Apache Kafka
Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, ref
4 min read
Spring Boot - Consume JSON Object From Kafka Topics
Apache Kafka is a publish-subscribe messaging system. A messaging system lets someone is sending messages between processes, applications, and servers. Broadly Speaking, Apache Kafka is software where topics (A topic might be a category) can be defined and further processed. Applications may connect
4 min read
Spring Boot Kafka Producer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot Kafka Consumer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Message Compression in Apache Kafka using Spring Boot
Generally, producers send text-based data, such as JSON data. It is essential to apply compression to the producer in this situation. Producer messages are transmitted uncompressed by default. There are two types of Kafka compression. 1. Producer-Level Kafka Compression When compression is enabled o
4 min read