Open In App

Hibernate Validator

Last Updated : 15 Dec, 2023
Like Article

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 with proper descriptions for each.



@NotNull A field annotated with this should not be null
@NotEmpty A field annotated with this should not be empty
@NotBlank This field should not be null and not empty and not blank
@Min Given Minimum value has to be satisfied
@Max Given Maximum value has to be satisfied
@Size(min=x, max=y) Field size should be less than or greater than the specified field size
@Email Email 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.


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


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


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


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


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).


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


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

In this article, let us see how to validate the data by using Hibernate validator. For that let us take a sample Maven Project containing a bean (model) class of a geekuser containing different attributes. We will see Hibernate Validator first before moving to the project.

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.

Project Structure:

Project Structure

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


<project xmlns=""
    <name>Hibernate Validator</name>
    <description>Basic Example for Java Bean Validation using Hibernate</description>

        <!-- Java bean validation API - Spec -->

        <!-- Hibernate validator - Bean validation API Implementation -->

        <!-- Verify validation annotations usage at compile time -->

        <!-- Unified Expression Language - Spec -->

        <!-- Unified Expression Language - Implementation -->


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


<!-- Verify validation annotations usage at compile time -->

While defining the bean class itself, we have to annotate according to our requirements


Entity contains all the fields required for GeekUser with applied annotaions


//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 = "Invalid number of articles. Maximum allowed is 5.")
    private String currentTimeOfWritingArticles;

    // Minimum allowed articles for review (min value 3)
    @Min(value = 3, message = "Invalid number of articles for review. Minimum should be 3.")
    private String 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 = {
    }, 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) {
        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



This class defines a user with various attributes and validation constraints using annotations.

  • User ID: Required, not null.
  • Username: Required, 3-20 characters long.
  • Email: Required, valid format.
  • Age: Digits only, max 3 digits.
  • Max articles/day: Max 5.
  • Min review articles: Min 3.
  • Proficiency 3: Required, not blank.
  • Proficiency 4: Optional, must be null.
  • Proficiency 5: Required, Y/N (case-insensitive).
  • Rating: Positive value only.
  • Blocklisted: Negative or zero.
  • Future date: Must be after today.
  • Future/present date: Today or later.
  • Past/present date: Today or earlier.
  • Range example: Between 1 and 3.
  • URL example: Valid URL format.
  • Credit card example: Valid credit card number.

Validator Example

While giving the annotations, provide the message correctly which will be given as an error message if there is a violation happens with the given annotation. Now let us see the testing file that contains both the valid and invalid user. Need to write the code to print the error messages in case of errors. A lot of attributes need to be validated, and as a group, they are tested.


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...");
        // Create an invalid user object with various errors
        GeekUser invalidUser = new GeekUser(null,
                                            new Date(), 

        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) {


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

        // Create a valid user object
        GeekUser validUser = new GeekUser(1L, 

        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) {


    // 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();


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,

So, by using these validation mechanisms, nicely we can validate data even for URLs, and Creditcard also. Annotations are user-friendly and according to our user requirements, they need to be applied and get the appropriate flow. This is an efficient way of validating the form data as well. Hibernate provides the facility effectively.


This code is validating user input using annotations and a validator

  • Code ha two parts one for a valid and other for invalid user data using annotations and a validator.
  • Method:
    • Create a validator factory and validator.
    • Define two GeekUser objects:
      • invalidUser: filled with invalid data to trigger errors (null ID, short name, etc.).
      • validUser: filled with valid data according to annotations.
    • Use the validator to check each user object.
    • Print any violation messages if found.
  • Validation annotations used:
    • @NotNull@NotEmpty@Size, etc. for basic checks.
    • @Email, @URL@CreditCardNumber for specific formats.
    • @Min, @Max@Range for value constraints.
    • @Future@PastOrPresent for date checks.
  • Output:
    • Lists any violation messages for invalid data, or prints “Valid user data provided.” for valid data.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads