Open In App

Hibernate Validator

Last Updated : 15 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Annotation

Usages

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

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

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

XML

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://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.

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

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

GeekUser

Entity contains all the fields required for GeekUser with applied annotaions

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 = "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 = {
        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

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.

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,

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.

Explanation

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
Previous
Next
Share your thoughts in the comments

Similar Reads