Java Bean Validation 2.0 – Hibernate Validator Example

Bean validation in Java is supported via JSR-303 (Bean Validation 1.0), JSR-349 (Bean Validation 1.1) and JSR 380 (Bean Validation 2.0).

In this post, we will learn to use hibernate validator to validate the fields in Java bean. Bean validation API offers some very useful annotations that can be applied on a bean property for the purpose of maintaining data integrity.

1. Maven

Given below are the required hibernate validator maven dependencies.

Bean validation allows expressions inside the error messages. To parse these expressions, we must add a dependency on both the expression language API and an implementation of that API. I have added these using javax.el-api specification which is implemented in javax.el from Jboss.

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

2. Bean Validation Example

2.1. Model annotated with JSR-380 annotations

package com.howtodoinjava.example.model;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

    @NotNull(message = "Please enter id")
    private Long id;

    @Size(max = 20, min = 3, message = "{}")
    @NotEmpty(message = "Please enter name")
    private String name;

    @Email(message = "{}")
    @NotEmpty(message = "Please enter email")
    private String email;

    public User(Long id, String name, String email) {
        super(); = id; = name; = email;

    //Setters and Getters

2.2. Default Interpolation

By default, all messages are resolved from file in classpath. If file does not exist, the message resolution does not happen. Username Email

2.3. Executing Validation

Now let’s execute the bean validation on User instance.

package com.howtodoinjava.example;

import java.util.Set;

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

import com.howtodoinjava.example.model.User;

public class TestHibernateValidator 
    public static void main(String[] args) 
        //Create ValidatorFactory which returns validator
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        //It validates bean instances
        Validator validator = factory.getValidator();

        User user = new User(null, "1", "");

        //Validate bean
        Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);

        //Show errors
        if (constraintViolations.size() > 0) {
            for (ConstraintViolation<User> violation : constraintViolations) {
        } else {
            System.out.println("Valid Object");

Program output:

Please enter id
Invalid Email
Invalid Username

3. Custom Resource Bundles

By default, framework picks up validation messages from file in classpath. We may configure the custom property files as below.

For example, put these two property files in classpath:


Add both property files to ResourceBundleMessageInterpolator.

Validator validator = Validation.byDefaultProvider()
                new ResourceBundleMessageInterpolator(
                        new AggregateResourceBundleLocator(

4. Custom Message Interpolation

4.1. Parameters resolution in runtime

During message resolution, you can use runtime values to make validation messages more meaningful. This parameter value resolution in messages happen in two ways:

  1. To resolve values in annotation attributes, simply enclose the with curly braces. E.g. {min} or {max}.
  2. To resolve field’s runtime value, use placeholder ${validatedValue}.

4.2. Parameter value resolution example

  • Property file with message and parameters.'${validatedValue}' is an invalid name. It must be minimum {min} chars and maximum {max} chars.
  • Bean field with validation annotation.
    @Size(max = 20, min = 3, message = "{}")
    private String name;
  • Resolved message in program output.
    User user = new User(23l, "xy", "");
    Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);

    Program Output.

    'xy' is an invalid name. It must be minimum 3 chars and maximum 20 chars.

5. Bean Validation Annotations List

Now when we know how to use hibernate validator in programmatic manner. Let’s go through all the annotations which you can use in bean classes.

5.1. Default Annotations

@Digits(integer=, fraction=)
Checks whether the annotated value is a number having up to integer digits and fraction fractional digits.
Checks whether the specified character sequence is a valid email address.
Checks whether the annotated value is less than or equal to the specified maximum.
Checks whether the annotated value is higher than or equal to the specified minimum
Checks that the annotated character sequence is not null and the trimmed length is greater than 0.
Checks whether the annotated element is not null nor empty.
Checks that the annotated value is null
Checks that the annotated value is not null
@Pattern(regex=, flags=)
Checks if the annotated string matches the regular expression regex considering the given flag match
@Size(min=, max=)
Checks if the annotated element’s size is between min and max (inclusive)
Checks if the element is strictly negative. Zero values are considered invalid.
Checks if the element is negative or zero.
Checks whether the annotated date is in the future.
Checks whether the annotated date is in the present or in the future.
Checks whether the annotated date is in the past or in the present.

5.2. Hibernate validator specific annotations

In addition to the constraints defined by the Bean Validation API, Hibernate Validator provides several useful custom constraints which are listed below.

@CreditCardNumber( ignoreNonDigitCharacters=)
Checks that the annotated character sequence passes the Luhn checksum test. Note, this validation aims to check for user mistakes, not credit card validity!
Checks that the currency unit of the annotated is part of the specified currency units.
Checks that the annotated character sequence is a valid EAN barcode. The default is EAN-13.
Checks that the annotated character sequence is a valid ISBN.
@Length(min=, max=)
Validates that the annotated character sequence is between min and max included.
@Range(min=, max=)
Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.
Checks that the annotated collection only contains unique elements.
Checks if the annotated character sequence is a valid URL according to RFC2396.

Drop me your questions in the comments section.

Happy Learning !!


Bean Validation 2.0
Hibernate Validator Annotation Processor

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Java Bean Validation 2.0 – Hibernate Validator Example”

  1. How to stop the next constraints checks for single field .
    for example there is bean User and has String userName;

    Certificate Number is mandatory

    here if first constraint fail means NotNull then i dont want check pattren check i have to stop here

    Certificate Number should not contain spaces


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.