Open In App

Spring Boot – Validation using Hibernate Validator

Last Updated : 26 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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).
@MinGiven Minimum value has to be satisfied
@MaxGiven Maximum value has to be satisfied
@SizeField size should be less than or greater than the specified field size
@EmailEmail can be validated with this
@PatternGiven 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


Project structure


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

Running th Application in the console


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

Output in POSTMAN

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.



Next Article

Similar Reads