Over a million developers have joined DZone.

Create Your Own Constraints With Bean Validation 2.0

DZone's Guide to

Create Your Own Constraints With Bean Validation 2.0

Take a look at how you can create and export your own custom constraints for Bean Validation with this step-by-step tutorial.

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

Data integrity is an important part of application logic. Bean Validation is an API that provides a facility for validating objects, objects members, methods, and constructors. This API allows developers to constrain once, validate everywhere. Bean Validation 2.0 is part of Java EE 8, but it can be used with plain Java SE.

Bean Validation 2.0 brings several built-in constraints, perhaps those are the most common used from small to large applications, some of them are: @NotNull, @Size, @Max, @Min, @Email.

But when built-in constraints are not enough for our applications, we can create our own constraints that can be used everywhere we need it.

Minimum Requirements

  • Java 8
  • Apache Maven 3.3.9 or higher

The Constraint

In our example, we want to constrain that only people over 18 years old can sign up on our website. The constraint must be composed of at least two Java classes: an annotation interface and a validator class. So, we named our constraint Age and our default validator AgeValidator.

The Pom.xml File

To start, we need to define our Maven dependencies. For bean validation, we use validation-api 2.0.0.Final and as our implementation, we use hibernate-validator 6.0.7.Final:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">





The Annotation Java Interface

Age will be our annotation type. It is similar to other annotation types. To define this annotation type as a Bean Validation Constraint, we need to add the annotation javax.validation.Constraint (@Constraint) in its declaration.

  • @Target: @Target is where our annotations can be used

  • @Retention:@Retention specifies how the marked annotation is stored. We choose RUNTIME, so it can be used by the runtime environment.

  • @Constraint: @Constraint marks an annotation as being a Bean Validation constraint. The element validatedBy specifies the classes implementing the constraint. We will update this element after we have created the Validator Class.

Our annotation type has four attributes: message, groups, payload, and value, and a nested annotation type: List.

  • String message defines the message that will be showed when the input data is not valid.

  • Class<?>[] groups() lets the developer select to split the annotations into different groups to apply different validations to each group-e.g., @Age(groups=MALE).

  • long value: The value that will be used to define whether the input value is valid or is not- e.g., @Age(value=18).

  • Class<? extends PayLoad> []payLoad(): Payloads are typically used to carry metadata information consumed by a validation client.

  • @interface List: Bean Validation 2.0 provides support for validating container elements by annotating type arguments of parameterized types. To give this characteristic to our constraint, we defined a nested annotation type named List.

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Constraint(validatedBy = { })
public @interface Age {

    String message() default "Must be greater than {value}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

    long value();

    @interface List {
        Age[] value();

The Java Validator Class

The Validator class must implement ConstraintValidator. It has two methods: initialize and isValid.

The method initialize will be used to establish the necessary attributes to execute the validation — in our case, the age 18 years.

isValid is the method that received the input value and decides whether it is valid or is not.

The implementation of ConstraintValidator<Age, LocalDate> says it accepts Age as an annotation and the input value must be a type of LocalDate:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class AgeValidator implements ConstraintValidator<Age, LocalDate> {

    protected long minAge;

    public void initialize(Age ageValue) {
        this.minAge = ageValue.value();

    public boolean isValid(LocalDate date, ConstraintValidatorContext constraintValidatorContext) {
        // null values are valid
        if ( date == null ) {
            return true;
        LocalDate today = LocalDate.now();
        return ChronoUnit.YEARS.between(date, today)>=minAge;

In order to define the default Validator for our Age Constraint, it is necessary to make a change to the Age annotations class. In our case, we say that AgeValidator is the implementation class for our constraint.

@Constraint(validatedBy = { AgeValidator.class })
public @interface Age {

Using the New Constraint

Now we can use our constraint wherever we need it. As with built-in constraints of Bean Validation, all we need to do is add our constraint to the property we want to validate and let Bean Validation 2.0 do its job.

@Age(value=18)private Date birthDate;

Note: If you want to use the constraint in others projects, you should package it as a JAR file (the interface annotation and the validator class).

That is it! Now you are ready to create your own Bean Validation constraints.


Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

java ,java ee 8 ,bean validation 2.0 ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}