Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Spring Boot – Validation using Hibernate Validator

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Hibernate validators are very useful and they provide the following annotations that are very helpful for software development.



@NotNullChar Sequence, Collection, Map, or Array object can be validated with this and they should not be null but can be empty
@NotEmptyChar Sequence, Collection, Map, or Array object can be validated with this and they should not be null and not empty
@NotBlankChar Sequence, Collection, Map, or Array objects can be validated with this and they should not be null and not empty and not blank
@MinGiven Minimum value has to get satisfied
@MaxGiven Maximum value has to get satisfied
@SizeField size should be less than or greater than the specified field size
@EmailEmail can be validated with this
@PatternGiven RegEx Pattern has to be satisfied.

Let us go with a sample project that includes Hibernate validator.

Example Project

Project Structure:

Project structure


This is the maven project and hence the required dependencies need to be placed in pom.xml

Mandatory dependency for hibernate validator:




<?xml version="1.0" encoding="UTF-8"?>
        <relativePath/> <!-- lookup parent from repository -->
    <!-- Must for hibernate validator-->
    <!-- dependency for automatic reloads or live reload of applications -->

Let us start with a bean class that can have the annotations


import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class GeekEmployee {   
    @NotBlank(message = "Please enter proper employee name")
    @Size(min=5, message = "Name should be atleast 5 characters")
    @Size(max=12, message = "Name should not be greater than 12 characters")
    private String geekEmployeeName;
    @NotNull(message = "Please enter a valid salary")
    @Min(value=1000, message = "Salary must be atleast 1000.00")
    @Max(value=40000, message = "Salary should not be greater than 40000.00")
    private Double salary;
    @Email(message = "Please enter a valid email Id", regexp="^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,5}")
    @NotNull(message = "Please enter a valid email Id")
    private String geekEmailId;
    @NotBlank(message = "Please enter qualifications")
    @NotNull(message = "Please enter qualifications")
    private String qualifications;
    public String getQualifications() {
        return qualifications;
    public void setQualifications(String qualifications) {
        this.qualifications = qualifications;
    public String getGeekEmployeeName() {
        return geekEmployeeName;
    public void setGeekEmployeeName(String geekEmployeeName) {
        this.geekEmployeeName = geekEmployeeName;
    public Double getSalary() {
        return salary;
    public void setSalary(Double salary) {
        this.salary = salary;
    public String getGeekEmailId() {
        return geekEmailId;
    public void setGeekEmailId(String geekEmailId) {
        this.geekEmailId = geekEmailId;

To collect all the errors, we need to have an “ExceptionHandler” and it is given below


import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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;
public class ExceptionHandler extends ResponseEntityExceptionHandler{
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception,
            HttpHeaders httpHeaders, HttpStatus httpStatus, WebRequest webRequest) {
        Map<String, Object> objectBody = new LinkedHashMap<>();
        objectBody.put("Current Timestamp", new Date());
        objectBody.put("Status", httpStatus.value());
        // Get all errors
        List<String> exceptionalErrors = exception.getBindingResult()
                .map(x -> x.getDefaultMessage())
        objectBody.put("Errors", exceptionalErrors);
        return new ResponseEntity<>(objectBody, httpStatus);

Let us try to save the geekemployees by accepting the inputs like “geekEmployeeName”,”salary”,”geekEmailId” and “qualifications”. We need a rest controller file to achieve the same.


import javax.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.RestController;
public class GeekEmplooyeeController {
    public ResponseEntity<GeekEmployee> saveEmployeeData (@Valid @RequestBody GeekEmployee geekEmployee) {
        return new ResponseEntity<GeekEmployee>(geekEmployee, HttpStatus.CREATED);

Our last step is to write the main class that starts the spring boot project. Via eclipse also it can be started as an ordinary java application or since it is a maven application, it can be started as

mvn spring-boot:run


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
public class ValidationApplication {
    public static void main(String[] args) {, args);

On running the application, in the console, we can see as follows


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

Output in Postman



By means of Hibernate validator, very easily front-end validations can be checked and that helps a lot in spring boot projects simply a dependency makes these kinds of validations to validate a page.

My Personal Notes arrow_drop_up
Last Updated : 07 Nov, 2022
Like Article
Save Article
Similar Reads
Related Tutorials