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.
Join the DZone community and get the full member experience.
Join For FreeData 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"
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>medellinJUG</groupId>
<artifactId>my-validator</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.ee.version>8.0</java.ee.version>
<java.se.version>1.8</java.se.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<org.hibernate.validator.version>6.0.7.Final</org.hibernate.validator.version>
<javax.validation.version>2.0.0.Final</javax.validation.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${org.hibernate.validator.version}</version>
</dependency>
</dependencies>
</project>
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;
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
@Documented
@Constraint(validatedBy = { })
public @interface Age {
String message() default "Must be greater than {value}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
long value();
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@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;
@Override
public void initialize(Age ageValue) {
this.minAge = ageValue.value();
}
@Override
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.
References
- Bean Validation site http://beanvalidation.org
Opinions expressed by DZone contributors are their own.
Comments