Java Bean Validation API is a specification which
- Providing data validation model via built-in and custom defined constraint annotations placed on class, field and method
Providing APIs to validate objects, object graphs, parameters and return values of methods and constructors
Defined in
javax.validation
package and available as a part of Java EE since Java 6
Hibernate Validator is an implementation of the API
In this tutorial, you will learn to implement an Hibernate Validator example to validate a data model
What you'll need
- JDK 8+ or OpenJDK 8+
- Maven 3+
Project structure
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── hellokoding
│ │ └── validation
│ │ ├── Main.java
│ │ ├── Product.java
│ │ ├── ProductCodeExisting.java
│ │ └── ProductCodeExistingValidator.java
│ └── resources
│ └── ValidationMessages.properties
└── pom.xml
Dependencies
Include hibernate-validator
into your pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
Unified Expression Language (EL) is also required for evaluating dynamic expressions in constraint violation messages when you run your application in Java SE. In Java EE, it is already provided by container
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>
Full content of pom.xml
as below
Define data model and validation constraints
Define data model
@NotNull
, @Size
and @Min
are built-in constraints
@ProductCodeExisting
is a custom constraint defined as below
{Size.name}
and {Min.price}
are message templates, theirs value will be replaced at run time by the below ValidationMessages.properties
Define custom constraint
An annotation type is defined using the @interface
keyword
All attributes of an annotation type are declared in a method-like manner, the following are required
an attribute
message
that returns the default violation messagesan attribute
groups
to restrict the set of constraints applied during validationan attribute
payload
used by clients of the Bean Validation API to assign custom payload objects to a constraint
{ProductCodeExisting}
is a message template. Its value will be replaced at run time by the below ValidationMessages.properties
Define custom constraint validator
Interpolate / customize the validation messages
Provide the message value when you express the constraint on defining data model, for example the constraint @NotNull(message = "must be not null")
of Product.java
, or add a file named ValidationMessages.properties
to the classpath
Bean Validation API uses the Unified Expression Language (EL) in constraint violation messages. The following objects available in the EL context
the attribute values of the constraint mapped to the attribute names, for example
{min}
and{max}
of the messageSize.name
mapped to@Size
constraint annotation inProduct.java
${validatedValue}
mapped to the current validated value of field, bean or method parametera bean named
formatter
exposing the var-arg method format(String format, Object… args) which behaves like java.util.Formatter.format(String format, Object… args)
Validating the constraints
Use the built-in ValidatorFactory
of javax.validation
to get a Validator
instance
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Use validator
to validate all constraints on object, for example
Set<ConstraintViolation<Product>> constraintViolations = validator.validate(product);
Type command mvn clean package exec:java
at your project root directory to run, expected output
PRICE 0.79 is less than 1
ID is required
NAME must be between 1 and 10 character long
DESCRIPTION must be not null
CODE "Hello Koding" is not existing
Source code
https://github.com/hellokoding/hellokoding-courses/tree/master/java-examples/java-bean-validation