Hibernate Validator

Last Updated : 23 Apr, 2026

Hibernate Validators offer field-level validation for every attribute of a bean class, which means you can easily validate a field content against null/not null, empty/not empty, with min/max value to a specific value, valid email, and valid credit card, etc., For each and everything, we have specific annotations.

  • All Hibernate Validators are available for both server and client application programming.
  • These Hibernate validators help in transparent integration because of their standard validation rules.

Hibernate Validators with descriptions

The table below contains the hibernate validators.

Annotation

Usages

@NotNullA field annotated with this should not be null
@NotEmptyA field annotated with this should not be empty
@NotBlankThis field should not be null and not empty and not blank
@MinGiven Minimum value has to be satisfied
@MaxGiven Maximum value has to be satisfied
@Size(min=x, max=y)Field size should be less than or greater than the specified field size
@EmailEmail can be validated with this
@Pattern(regexp="pattern")Given RegEx Pattern has to be satisfied.

@Digits(integer=x, fraction=y)

Validates that the field value consists only of digits, with the specified number of integer and fractional digits allowed.

@Posititve

The field value must be a positive number (greater than zero).

@NegativeOrZero

The field value must be either zero or a negative number.

@Future

The field value must represent a date and time in the future (after the current instant).

@FutureOrPresent

The field value must represent a date and time either in the present or the future.

@PastOrPresent

The field value must represent a date and time either in the past or the present.

@Range(min=x, max=y)

The field value must be within the specified range (inclusive of both min and max values).

@URL

Validates the field as a valid URL according to a predefined regex pattern.

@CreditCardNumber

Validates the field as a valid credit card number according to the Luhn algorithm.

Example Project

In the example we will create a GeekUser entity with all the fields annotated with some hibernate validators, then we will try to create a valid object of from it and bring the output on the console.

Step 1: Create Maven Project

  • Create a Maven project (e.g., in Eclipse/IntelliJ)
  • Project name: Hibernate-Validator-Java-Bean-Validation-Sample

Project Structure:

Project Structure
 

Step 2: Add Required Dependencies

As it is the maven project, all the dependencies are in pom.xml

XML
<project xmlns="https://maven.apache.org/POM/4.0.0"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
                        https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gfg.validate</groupId>
    <artifactId>Hibernate-Validator-Java-Bean-Validation-Sample</artifactId>
    <version>1.0.0</version>
    <name>Hibernate Validator</name>
    <description>Basic Example for Java Bean Validation using Hibernate</description>

    <dependencies>
        <!-- Java bean validation API - Spec -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

        <!-- Hibernate validator - Bean validation API Implementation -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.11.Final</version>
        </dependency>

        <!-- Verify validation annotations usage at compile time -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-annotation-processor</artifactId>
            <version>6.0.11.Final</version>
        </dependency>

        <!-- Unified Expression Language - Spec -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.1-b06</version>
        </dependency>

        <!-- Unified Expression Language - Implementation -->
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.6</version>
        </dependency>
    </dependencies>

</project>

Below two are mandatory dependencies that are required to use the annotations that got used in the code.

XML
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.0.11.Final</version>
</dependency>

<!-- Verify validation annotations usage at compile time -->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator-annotation-processor</artifactId>
  <version>6.0.11.Final</version>
</dependency>

Step 3: Create Entity Class

  • Create a class GeekUser.java. Add Fields with Validation Annotations.
  • Entity contains all the fields required for GeekUser with applied annotaions

GeekUser

Java
//Entity of GeekUsers

import java.util.Date;

import javax.validation.constraints.Digits;
import javax.validation.constraints.Email;
import javax.validation.constraints.Future;
import javax.validation.constraints.FutureOrPresent;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NegativeOrZero;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.PastOrPresent;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Pattern.Flag;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.CreditCardNumber;
import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.URL;

public class GeekUser {

    // User ID (required, not null)
    @NotNull(message = "Invalid ID. Please enter your ID.")
    private Long geekUserId;

    // User name (required, not empty, size between 3 and 20)
    @Size(max = 20, min = 3, message = "Invalid name. Size should be between 3 to 20.")
    @NotEmpty(message = "Please enter your name.")
    private String geekUserName;

    // User email ID (required, not empty, valid email format)
    @Email(message = "Invalid email address. Please enter a proper email ID.")
    @NotEmpty(message = "Please enter your email ID.")
    private String geekUserEmailId;

    // User age (digits only, 3 digits max)
    @Digits(integer = 3, fraction = 0, message = "Invalid age. Maximum valid number for age is 3 digits.")
    private int geekAge;

    // Maximum allowed articles to write per day (max value 5)
    @Max(value = 5, message = "Maximum allowed is 5.")
    private int currentTimeOfWritingArticles;

    // Minimum allowed articles for review (min value 3)
    @Min(value = 3, message = "Minimum should be 3.")
    private int allowedForArticleReviewing;

    // Proficiency level 3 (required, not blank)
    @NotBlank(message = "Proficiency level 3 should not be blank.")
    private String proficiency3;

    // Proficiency level 4 (optional, must be null)
    @Null(message = "Proficiency level 4 should be null.")
    private String proficiency4;

    // Proficiency level 5 (required, must match Y/N pattern, case-insensitive)
    @Pattern(regexp = "YN", flags = {
        Pattern.Flag.CASE_INSENSITIVE
    }, message = "Invalid proficiency level 5. Enter Y or N.")
    private String proficiency5;

    // User rating (positive value only)
    @Positive(message = "Invalid rating. Value should be positive.")
    private int rating;

    // Blocklisted status (negative or zero only)
    @NegativeOrZero(message = "Invalid blocklisted status. Input number should be negative or zero.")
    private int blocklisted;

    // Future date (must be after today)
    @Future(message = "Invalid date. It should be provided as a future date.")
    private Date futureDate;

    // Future or present date (must be today or later)
    @FutureOrPresent(message = "Invalid date. It should be provided as a future or present date.")
    private Date futureOrPresent;

    // Past or present date (must be today or earlier)
    @PastOrPresent(message = "Invalid date. It should be provided as a past or present date.")
    private Date pastOrPresent;

    // Range example (value between 1 and 3)
    @Range(min = 1, max = 3, message = "Invalid range. Range should be within 1 to 3.")
    private int rangeExample;

    // URL example (must be a valid URL)
    @URL(message = "Invalid URL. Please provide a valid URL.")
    private String urlExample;

    // Credit card example (must be a valid credit card number)
    @CreditCardNumber(message = "Invalid credit card number. It should not contain invalid characters.")
    private String creditCardExample;

    /**
     * @param geekUserId - It should not be null 
     * @param geekUserName - It should not be empty and its size should be between 3 to 20
     * @param geekUserEmailId - It should not be empty and should be a proper emailId
     * @param geekAge - Age value should be in 3 digit
     * @param currentTimeOfWritingArticles - Maximum currentTimeOfWritingArticles  is 5
     * @param proficiency2 - Minimum Length of proficiency2  is 3
     * @param proficiency3 - Proficiency 3 Should not be blank
     * @param proficiency4 - Proficiency 4 should be null
     * @param proficiency5 - Invalid Proficiency 5, Enter text not matches with the standards
     * @param rating - Invalid Rating, Value should be positive
     * @param blocklisted - Invalid value for blocklisted, Input Number should be negative or Zero
     * @param futureDate - Invalid date, It should be provided as future date
     * @param futureOrPresent - Invalid date, It should be as future or present date
     * @param pastOrPresent - Invalid date, It should be as Past or present date
     * @param rangeExample - Invalid Range is given, Range should be within 1 to 3
     * @param urlExample - Invalid Url, Please provide a valid URL
     * @param creditCardExample - Invalid Creditcard, It should not contain invalid character
     */
    public GeekUser(Long geekUserId, String geekUserName, String geekUserEmailId, int geekAge,
        String currentTimeOfWritingArticles, String proficiency2,
        String proficiency3, String proficiency4,
        String proficiency5, int rating, int blocklisted,
        Date futureDate, Date futureOrPresent, Date pastOrPresent,
        int rangeExample, String urlExample, String creditCardExample) {
        super();
        this.geekUserId = geekUserId;
        this.geekUserName = geekUserName;
        this.geekUserEmailId = geekUserEmailId;
        this.geekAge = geekAge;
        this.currentTimeOfWritingArticles = currentTimeOfWritingArticles;
        this.allowedForArticleReviewing = proficiency2;
        this.proficiency3 = proficiency3;
        this.proficiency4 = proficiency4;
        this.proficiency5 = proficiency5;
        this.rating = rating;
        this.blocklisted = blocklisted;
        this.futureDate = futureDate;
        this.futureOrPresent = futureOrPresent;
        this.pastOrPresent = pastOrPresent;
        this.rangeExample = rangeExample;
        this.urlExample = urlExample;
        this.creditCardExample = creditCardExample;
    }

    // Setter And Getter

}

Explanation:

  • The GeekUser class represents a Java entity with validation constraints using Hibernate Validator (JSR-380).
  • It ensures that user data like name, email, age, and other fields follow specific rules before processing.
  • Annotations such as @NotNull, @Email, @Size, and @Pattern help enforce data integrity.
  • It includes validations for numeric limits, date conditions (past/future), URLs, and credit card formats.
  • Overall, it demonstrates a clean and declarative way to apply field-level validations in Java applications.

Validator Example

Provide proper messages in annotations so they display when validation fails. Create a test class with both valid and invalid user objects. Use a validator to check all fields together and print error messages if any violations occur.

Steps of Validator Example

  1. Create ValidatorFactory and Validator to initialize validation.
  2. Create an invalidUser object with incorrect data to trigger errors.
  3. Validate the invalid object using validator.validate().
  4. Store validation errors in ConstraintViolation set.
  5. Check if violations exist.
  6. Loop through violations and print error messages.
  7. Create a validUser object with correct data.
  8. Validate the valid object using validator.validate().
  9. Check if violations are empty.
  10. If no errors -> print "Valid user data provided."
  11. Use utility method getPastOrFutureDate() for testing date validations.
  12. Observe output -> errors for invalid data, success message for valid data.
Java
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class ValidatorExample {

      //Main Method
    public static void main(String[] args) {

        // Create a validator factory and validator
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        // **Check for invalid user data**
        System.out.println("Checking for invalid user data...");
        System.out.println("-----------------------------------");
      
        // Create an invalid user object with various errors
        GeekUser invalidUser = new GeekUser(null,
                                            "a",
                                            "test123",
                                            12456,
                                            "Javatechnology",
                                            "db", 
                                            "", 
                                            "1234", 
                                            "y", 
                                            -2, 
                                            1,
                                            new Date(), 
                                            getPastOrFutureDate(-2), 
                                            getPastOrFutureDate(2),
                                            5, 
                                            "sample1.com", 
                                            "123@");

        Set<ConstraintViolation<GeekUser>> violations = validator.validate(invalidUser);

        if (violations.isEmpty()) {
            System.out.println("Valid user data provided.");
        } else {
            System.out.println("Invalid user data found:");
            for (ConstraintViolation<GeekUser> violation : violations) {
                System.out.println(violation.getMessage());
            }
        }

        System.out.println("-----------------------------------");
        System.out.println();

        // **Check for valid user data**
        System.out.println("Checking for valid user data...");
        System.out.println("-----------------------------------");

        // Create a valid user object
        GeekUser validUser = new GeekUser(1L, 
                                          "geekauthor", 
                                          "geeka@gmail.com",
                                          16, 
                                          "4", 
                                          "3", 
                                          "ML", 
                                          null, 
                                          "YN", 
                                          2, 
                                          0,
                                          getPastOrFutureDate(2), 
                                          getPastOrFutureDate(1),
                                          getPastOrFutureDate(-2), 
                                          2, 
                                          "https://www.geeksforgeeks.org/", 
                                          "6011111111111117");

        violations = validator.validate(validUser);

        if (violations.isEmpty()) {
            System.out.println("Valid user data provided.");
        } else {
            System.out.println("Invalid user data found:");
            for (ConstraintViolation<GeekUser> violation : violations) {
                System.out.println(violation.getMessage());
            }
        }

        System.out.println("-----------------------------------");
    }

    // Utility method to generate past or future dates
    public static Date getPastOrFutureDate(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }
}

Output

On execution of the above code, we see the below output in the console.

So error messages help us to identify what is wrong and we can correct it appropriately. At the same time, if a few inputs are correct and a few are wrong, then the relevant error messages are seen. If all are correct,

Hibernate validation allows easy checking of data like URLs and credit cards using annotations. It is user-friendly, efficient, and helps ensure correct form data based on requirements.

Explanation

  • Validates user data using annotations and a validator
  • Contains two objects: invalidUser and validUser
  • invalidUser -> triggers validation errors
  • validUser -> follows all validation rules
  • Validator checks objects using validate() method
  • Prints error messages if violations exist
  • Uses annotations like @NotNull, @Email, @Min, @Future
  • Output -> errors for invalid data or "Valid user data provided." for valid data
Comment