Hibernate.orgCommunity Documentation
2017-03-15
ParameterMessageInterpolatorResourceBundleLocatorParameterNameProvider@Future and@PastValidating data is a common task that occurs throughout all application layers, from thepresentation to the persistence layer. Often the same validation logic is implemented in each layerwhich is time consuming and error-prone. To avoid duplication of these validations, developers oftenbundle validation logic directly into the domain model, cluttering domain classes with validationcode which is really metadata about the class itself.

JSR 349 - Bean Validation 1.1 - defines a metadata model and API for entity and method validation.The default metadata source are annotations, with the ability to override and extend the meta-datathrough the use of XML. The API is not tied to a specific application tier nor programming model. Itis specifically not tied to either web or persistence tier, and is available for both server-sideapplication programming, as well as rich client Swing application developers.

Hibernate Validator is the reference implementation of this JSR 349. The implementation itself aswell as the Bean Validation API and TCK are all provided and distributed under theApache Software License 2.0.
This chapter will show you how to get started with Hibernate Validator, the reference implementation (RI) of Bean Validation. For the following quick-start you need:
In order to use Hibernate Validator within a Maven project, simply add the following dependency toyourpom.xml:
Example 1.1. Hibernate Validator Maven dependency
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.5.Final</version></dependency>This transitively pulls in the dependency to the Bean Validation API(javax.validation:validation-api:1.1.0.Final).
Hibernate Validator requires an implementation of the Unified Expression Language(JSR 341) for evaluating dynamic expressions in constraintviolation messages (seeSection 4.1, “Default message interpolation”). When your application runs in a Java EEcontainer such as JBoss AS, an EL implementation is already provided by the container. In a Java SEenvironment, however, you have to add an implementation as dependency to your POM file. For instanceyou can add the following two dependencies to use the JSR 341referenceimplementation:
Example 1.2. Maven dependencies for Unified EL reference implementation
<dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>2.2.4</version></dependency><dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.4</version></dependency>For environments where one cannot provide a EL implementation Hibernate Validator is offering aSection 11.7, “ParameterMessageInterpolator”. However, the use of this interpolatoris not Bean Validation specification compliant.
Bean Validation defines integration points with CDI (Contexts and Dependency Injection for JavaTMEE,JSR 346). If your application runs in anenvironment which does not provide this integration out of the box, you may use the HibernateValidator CDI portable extension by adding the following Maven dependency to your POM:
Example 1.3. Hibernate Validator CDI portable extension Maven dependency
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator-cdi</artifactId> <version>5.2.5.Final</version></dependency>Note that adding this dependency is usually not required for applications running on a Java EEapplication server. You can learn more about the integration of Bean Validation and CDI inSection 10.3, “CDI”.
Hibernate Validator supports running with asecurity manager being enabled.To do so, you must assign several permissions to the Hibernate Validator and the Bean Validation API code bases.The following shows how to do this via apolicy file as processed by the Java default policy implementation:
Example 1.4. Policy file for using Hibernate Validator with a security manager
grant codeBase "file:path/to/hibernate-validator-5.2.5.Final.jar" { permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; permission java.lang.RuntimePermission "accessDeclaredMembers"; permission java.lang.RuntimePermission "setContextClassLoader"; // Only needed when working with XML descriptors (validation.xml or XML constraint mappings) permission java.util.PropertyPermission "mapAnyUriToUri", "read";};grant codeBase "file:path/to/validation-api-1.1.0.Final.jar" { permission java.io.FilePermission "path/to/hibernate-validator-5.2.5.Final.jar", "read";};All API invocations requiring special permissions are done via privileged actions.This means only Hibernate Validator and the Bean Validation API themselves need the listed permissions.You don’t need to assign any permissions to other code bases calling Hibernate Validator.
Lets dive directly into an example to see how to apply constraints.
Example 1.5. Class Car annotated with constraints
package org.hibernate.validator.referenceguide.chapter01;import javax.validation.constraints.Min;import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;public class Car { @NotNull private String manufacturer; @NotNull @Size(min = 2, max = 14) private String licensePlate; @Min(2) private int seatCount; public Car(String manufacturer, String licencePlate, int seatCount) { this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; } //getters and setters ...}The@NotNull,@Size and@Min annotations are used to declare the constraints which should be appliedto the fields of a Car instance:
manufacturer must never benulllicensePlate must never benull and must be between 2 and 14 characters longseatCount must be at least 2You can find the complete source code of all examples used in this reference guide in the HibernateValidatorsource repositoryon GitHub.
To perform a validation of these constraints, you use aValidator instance. Let’s have a look at aunit test forCar:
Example 1.6. Class CarTest showing validation examples
package org.hibernate.validator.referenceguide.chapter01;import java.util.Set;import javax.validation.ConstraintViolation;import javax.validation.Validation;import javax.validation.Validator;import javax.validation.ValidatorFactory;import org.junit.BeforeClass;import org.junit.Test;import static org.junit.Assert.assertEquals;public class CarTest { private static Validator validator; @BeforeClass public static void setUpValidator() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); } @Test public void manufacturerIsNull() { Car car = new Car( null, "DD-AB-123", 4 ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() ); } @Test public void licensePlateTooShort() { Car car = new Car( "Morris", "D", 4 ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); assertEquals( "size must be between 2 and 14", constraintViolations.iterator().next().getMessage() ); } @Test public void seatCountTooLow() { Car car = new Car( "Morris", "DD-AB-123", 1 ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); assertEquals( "must be greater than or equal to 2", constraintViolations.iterator().next().getMessage() ); } @Test public void carIsValid() { Car car = new Car( "Morris", "DD-AB-123", 2 ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); assertEquals( 0, constraintViolations.size() ); }}In thesetUp() method aValidator object is retrieved from theValidatorFactory. AValidatorinstance is thread-safe and may be reused multiple times. It thus can safely be stored in a staticfield and be used in the test methods to validate the differentCar instances.
Thevalidate() method returns a set ofConstraintViolation instances, which you can iterate over inorder to see which validation errors occurred. The first three test methods show some expectedconstraint violations:
@NotNull constraint onmanufacturer is violated inmanufacturerIsNull()@Size constraint onlicensePlate is violated inlicensePlateTooShort()@Min constraint onseatCount is violated inseatCountTooLow()If the object validates successfully,validate() returns an empty set as you can see incarIsValid().
Note that only classes from the packagejavax.validation are used. These are provided from the BeanValidation API. No classes from Hibernate Validator are directly referenced, resulting in portablecode.
Java 8 introduces several enhancements which are valuable from a Hibernate Validator point of view.This section briefly introduces the Hibernate Validator features based on Java 8.They are only available in Hibernate Validator 5.2 and later.
In Java 8 it is possible to use annotations in any location a type is used. This includes typearguments. Hibernate Validator supports the validation of constraints defined on type argumentsof collections, maps, and custom parameterized types. TheSection 2.1.3, “Type argument constraints” chapterprovides further information on how to apply and use type argument constraints.
The Java 8 Reflection API can now retrieve the actual parameter names of a method or constructor.Hibernate Validator uses this ability to report the actual parameter names instead ofarg0,arg1, etc. TheSection 8.2.4, “ParameterNameProvider” chapter explains how to use the new reflectionbased parameter name provider.
Java 8 introduces a new date/time API. Hibernate Validator provides full support for the new APIwhere@Future and@Past constraints can be applied on the new types. The tableTable 2.2, “Bean Validation constraints” shows the types supported for@Future and@Past, including the typesfrom the new API.
Hibernate Validator provides also support for Java 8Optional type, by unwrapping theOptionalinstance and validating the internal value.Section 11.11.1, “Optional unwrapper” provides examples and afurther discussion.
That concludes the 5 minute tour through the world of Hibernate Validator and Bean Validation.Continue exploring the code examples or look at further examples referenced inChapter 13,Further reading.
To learn more about the validation of beans and properties, just continue readingChapter 2,Declaring and validating bean constraints. If you are interested in using Bean Validation for the validation ofmethod pre- and postcondition refer toChapter 3,Declaring and validating method constraints. In case your application hasspecific validation requirements have a look atChapter 6,Creating custom constraints.
In this chapter you will learn how to declare (seeSection 2.1, “Declaring bean constraints”) andvalidate (seeSection 2.2, “Validating bean constraints”) bean constraints.Section 2.3, “Built-in constraints” provides an overview of all built-in constraints coming withHibernate Validator.
If you are interested in applying constraints to method parameters and return values, refer toChapter 3,Declaring and validating method constraints.
Constraints in Bean Validation are expressed via Java annotations. In this section you will learnhow to enhance an object model with these annotations. There are the following three types of beanconstraints:
Not all constraints can be placed on all of these levels. In fact, none of the default constraintsdefined by Bean Validation can be placed at class level. Thejava.lang.annotation.Target annotationin the constraint annotation itself determines on which elements a constraint can be placed. SeeChapter 6,Creating custom constraints for more information.
Constraints can be expressed by annotating a field of a class.Example 2.1, “Field-level constraints” shows a fieldlevel configuration example:
Example 2.1. Field-level constraints
package org.hibernate.validator.referenceguide.chapter02.fieldlevel;public class Car {@NotNullprivate String manufacturer;@AssertTrueprivate boolean isRegistered;public Car(String manufacturer, boolean isRegistered) {this.manufacturer = manufacturer;this.isRegistered = isRegistered;}//getters and setters...}When using field-level constraints field access strategy is used to access the value to bevalidated. This means the validation engine directly accesses the instance variable and does notinvoke the property accessor method even if such an accessor exists.
Constraints can be applied to fields of any access type (public, private etc.). Constraints onstatic fields are not supported, though.
When validating byte code enhanced objects property level constraints should be used, because thebyte code enhancing library won’t be able to determine a field access via reflection.
If your model class adheres to theJavaBeans standard, itis also possible to annotate the properties of a bean class instead of its fields.Example 2.2, “Property-level constraints” uses the same entity as inExample 2.1, “Field-level constraints”, however, property levelconstraints are used.
Example 2.2. Property-level constraints
package org.hibernate.validator.referenceguide.chapter02.propertylevel;public class Car {private String manufacturer;private boolean isRegistered;public Car(String manufacturer, boolean isRegistered) {this.manufacturer = manufacturer;this.isRegistered = isRegistered;}@NotNullpublic String getManufacturer() {return manufacturer;}public void setManufacturer(String manufacturer) {this.manufacturer = manufacturer;}@AssertTruepublic boolean isRegistered() {return isRegistered;}public void setRegistered(boolean isRegistered) {this.isRegistered = isRegistered;}}The property’s getter method has to be annotated, not its setter. That way also read-only propertiescan be constrained which have no setter method.
When using property level constraints property access strategy is used to access the value to bevalidated, i.e. the validation engine accesses the state via the property accessor method.
It is recommended to stick either to fieldor property annotations within one class. It is notrecommended to annotate a fieldand the accompanying getter method as this would cause the fieldto be validated twice.
Starting from Java 8, it is possible to specify constraints directly on the type argument of aparameterized type. However, this requires thatElementType.TYPE_USE is specified via@Targetin the constraint definition. To maintain backwards compatibility, built-in Bean Validation as well asHibernate Validator specific constraints do not yet specifyElementType.TYPE_USE. To make use oftype argument constraints, custom constraints must be used (seeChapter 6,Creating custom constraints).
Hibernate Validator validates type arguments constraints specified on collections, map values,java.util.Optional, and custom parameterized types.
When applying constraints on anIterable type argument, Hibernate Validator will validate eachelement.Example 2.3, “Type argument constraint onList” shows an example of aList with a type argument constraint.
Example 2.3. Type argument constraint onList
package org.hibernate.validator.referenceguide.chapter02.typeargument;public class Car {@Validprivate List<@ValidPart String> parts = new ArrayList<>();public void addPart(String part) {parts.add( part );}//...}Car car = Car();car.addPart( "Wheel" );car.addPart( null );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals("'null' is not a valid car part.",constraintViolations.iterator().next().getMessage());assertEquals( "parts[1]", constraintViolations.iterator().next().getPropertyPath().toString() );Type argument constraints are also validated for map values. Constraints on the key are ignored.Example 2.4, “Type argument constraint on maps” shows an example of aMap value with a typeargument constraint.
Example 2.4. Type argument constraint on maps
package org.hibernate.validator.referenceguide.chapter02.typeargument;public class Car {public static enum FuelConsumption {CITY,HIGHWAY}@Validprivate EnumMap<FuelConsumption, @MaxAllowedFuelConsumption Integer> fuelConsumption = new EnumMap<>( FuelConsumption.class );public void setFuelConsumption(FuelConsumption consumption, int value) {fuelConsumption.put( consumption, value );} //...}Car car = new Car();car.setFuelConsumption( Car.FuelConsumption.HIGHWAY, 20 );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals( "20 is outside the max fuel consumption.", constraintViolations.iterator().next().getMessage() );When applying a constraint on the type argument ofOptional, Hibernate Validator will automaticallyunwrap the type and validate the internal value.Example 2.5, “Type argument constraint on Optional” showsan example of anOptional with a type argument constraint.
Example 2.5. Type argument constraint on Optional
package org.hibernate.validator.referenceguide.chapter02.typeargument;import java.util.ArrayList;import java.util.EnumMap;import java.util.List;import java.util.Optional;import javax.validation.Valid;public class Car {private Optional<@MinTowingCapacity(1000) Integer> towingCapacity = Optional.empty();public void setTowingCapacity(Integer alias) {towingCapacity = Optional.of( alias );} //...}Car car = Car();car.setTowingCapacity( 100 );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals( "Not enough towing capacity.", constraintViolations.iterator().next().getMessage() );assertEquals( "towingCapacity", constraintViolations.iterator().next().getPropertyPath().toString() );Type arguments constraints can with two restrictions also be used with custom types. First, aValidatedValueUnwrapper must be registered for the custom type allowing to retrievethe value to validate (seeSection 11.11, “Unwrapping values”). Second, only types with one type argumentsare supported. Parameterized types with two or more type arguments are not checked for type argumentconstraints. This limitation might change in future versions.
Example 2.6, “Type argument constraint on custom parameterized type” shows an example of a customparameterized type with a type argument constraint.
Example 2.6. Type argument constraint on custom parameterized type
package org.hibernate.validator.referenceguide.chapter02.typeargument;public class Car {private GearBox<@MinTorque(100) Gear> gearBox;public void setGearBox(GearBox<Gear> gearBox) {this.gearBox = gearBox;}//...}package org.hibernate.validator.referenceguide.chapter02.typeargument;public class GearBox<T extends Gear> {private final T gear;public GearBox(T gear) {this.gear = gear;}public Gear getGear() {return this.gear;}}package org.hibernate.validator.referenceguide.chapter02.typeargument;public class Gear {private final Integer torque;public Gear(Integer torque) {this.torque = torque;}public Integer getTorque() {return torque;}public static class AcmeGear extends Gear {public AcmeGear() {super( 100 );}}}package org.hibernate.validator.referenceguide.chapter02.typeargument;public class GearBoxUnwrapper extends ValidatedValueUnwrapper<GearBox> {@Overridepublic Object handleValidatedValue(GearBox gearBox) {return gearBox == null ? null : gearBox.getGear();}@Overridepublic Type getValidatedValueType(Type valueType) {return Gear.class;}}Car car = Car();car.setGearBox( new GearBox<>( new Gear.AcmeGear() ) );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals( "Gear is not providing enough torque.", constraintViolations.iterator().next().getMessage() );assertEquals( "gearBox", constraintViolations.iterator().next().getPropertyPath().toString() );Last but not least, a constraint can also be placed on the class level. In this case not a singleproperty is subject of the validation but the complete object. Class-level constraints are useful ifthe validation depends on a correlation between several properties of an object.
The Car class inExample 2.7, “Class-level constraint” has the two attributesseatCount andpassengers and itshould be ensured that the list of passengers has not more entries than seats are available. Forthat purpose the@ValidPassengerCount constraint is added on the class level. The validator of thatconstraint has access to the completeCar object, allowing to compare the numbers of seats andpassengers.
Refer toSection 6.2, “Class-level constraints” to learn in detail how to implement this customconstraint.
Example 2.7. Class-level constraint
package org.hibernate.validator.referenceguide.chapter02.classlevel;@ValidPassengerCountpublic class Car {private int seatCount;private List<Person> passengers;//...}When a class implements an interface or extends another class, all constraint annotations declaredon the super-type apply in the same manner as the constraints specified on the class itself. To makethings clearer let’s have a look at the following example:
Example 2.8. Constraint inheritance
package org.hibernate.validator.referenceguide.chapter02.inheritance;public class Car {private String manufacturer;@NotNullpublic String getManufacturer() {return manufacturer;}//...}package org.hibernate.validator.referenceguide.chapter02.inheritance;public class RentalCar extends Car {private String rentalStation;@NotNullpublic String getRentalStation() {return rentalStation;}//...}Here the classRentalCar is a subclass ofCar and adds the propertyrentalStation. If an instance ofRentalCar is validated, not only the@NotNull constraint onrentalStation is evaluated, but also theconstraint onmanufacturer from the parent class.
The same would be true, ifCar was not a superclass but an interface implemented byRentalCar.
Constraint annotations are aggregated if methods are overridden. So ifRentalCar overrode thegetManufacturer() method fromCar, any constraints annotated at the overriding method would beevaluated in addition to the@NotNull constraint from the superclass.
The Bean Validation API does not only allow to validate single class instances but also completeobject graphs (cascaded validation). To do so, just annotate a field or property representing areference to another object with@Valid as demonstrated inExample 2.9, “Cascaded validation”.
Example 2.9. Cascaded validation
package org.hibernate.validator.referenceguide.chapter02.objectgraph;public class Car {@NotNull@Validprivate Person driver;//...}package org.hibernate.validator.referenceguide.chapter02.objectgraph;public class Person {@NotNullprivate String name;//...}If an instance ofCar is validated, the referencedPerson object will be validated as well, as thedriver field is annotated with@Valid. Therefore the validation of aCar will fail if thename fieldof the referencedPerson instance isnull.
The validation of object graphs is recursive, i.e. if a reference marked for cascaded validationpoints to an object which itself has properties annotated with@Valid, these references will befollowed up by the validation engine as well. The validation engine will ensure that no infiniteloops occur during cascaded validation, for example if two objects hold references to each other.
Note thatnull values are getting ignored during cascaded validation.
Object graph validation also works for collection-typed fields. That means any attributes that
java.lang.Iterable (especiallyCollection,List andSet)java.util.Mapcan be annotated with@Valid, which will cause each contained element to be validated, when theparent object is validated.
Example 2.10. Cascaded validation of a collection
package org.hibernate.validator.referenceguide.chapter02.objectgraph.list;public class Car {@NotNull@Validprivate List<Person> passengers = new ArrayList<Person>();//...}So when validating an instance of theCar class shown inExample 2.10, “Cascaded validation of a collection”, aConstraintViolation will be created, if any of thePerson objects contained in the passengers listhas anull name.
TheValidator interface is the most important object in Bean Validation. The next section shows howto obtain anValidator instance. Afterwards you’ll learn how to use the different methods of theValidator interface.
The first step towards validating an entity instance is to get hold of aValidator instance. Theroad to this instance leads via theValidation class and aValidatorFactory. The easiest way is touse the static methodValidation#buildDefaultValidatorFactory():
Example 2.11. Validation#buildDefaultValidatorFactory()
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();This bootstraps a validator in the default configuration. Refer toChapter 8,Bootstrapping tolearn more about the different bootstrapping methods and how to obtain a specifically configuredValidator instance.
TheValidator interface contains three methods that can be used to either validate entire entitiesor just single properties of the entity.
All three methods return aSet<ConstraintViolation>. The set is empty, if the validation succeeds.Otherwise aConstraintViolation instance is added for each violated constraint.
All the validation methods have a var-args parameter which can be used to specify, which validationgroups shall be considered when performing the validation. If the parameter is not specified thedefault validation group (javax.validation.groups.Default) is used. The topic of validation groupsis discussed in detail inChapter 5,Grouping constraints.
Use thevalidate() method to perform validation of all constraints of a given bean.Example 2.12, “UsingValidator#validate()” shows the validation of an instance of theCar class fromExample 2.2, “Property-level constraints” which fails to satisfy the@NotNull constraint on themanufacturerproperty. The validation call therefore returns oneConstraintViolation object.
Example 2.12. UsingValidator#validate()
Car car = new Car( null, true );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );With help of thevalidateProperty() you can validate a single named property of a given object. Theproperty name is the JavaBeans property name.
Example 2.13. UsingValidator#validateProperty()
Car car = new Car( null, true );Set<ConstraintViolation<Car>> constraintViolations = validator.validateProperty(car,"manufacturer");assertEquals( 1, constraintViolations.size() );assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );By using thevalidateValue() method you can check whether a single property of a given class can bevalidated successfully, if the property had the specified value:
Example 2.14. UsingValidator#validateValue()
Set<ConstraintViolation<Car>> constraintViolations = validator.validateValue(Car.class,"manufacturer",null);assertEquals( 1, constraintViolations.size() );assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );---@Valid is not honored byvalidateProperty() orvalidateValue().
Validator#validateProperty() is for example used in the integration of Bean Validation into JSF 2(seeSection 10.2, “JSF & Seam”) to perform a validation of the values entered into a formbefore they are propagated to the model.
Now it is time to have a closer look at what aConstraintViolation is. Using the different methodsofConstraintViolation a lot of useful information about the cause of the validation failure can bedetermined.Table 2.1, “The variousConstraintViolation methods” gives an overview of these methods. The values in the"Example" column refer toExample 2.12, “UsingValidator#validate()”.
Table 2.1. The variousConstraintViolation methods
| Method | Usage | Example |
|---|---|---|
| The interpolated error message | "may not be null" |
| The non-interpolated error message | "{… NotNull.message}" |
| The root bean being validated | car |
| The class of the root bean being validated |
|
| If a bean constraint, the bean instance the constraint is applied on; If a property constraint, the bean instance hosting the property the constraint is applied on |
|
| The property path to the validated value from root bean | contains one node with kind |
| The value failing to pass the constraint |
|
| Constraint metadata reported to fail | descriptor for |
Hibernate Validator comprises a basic set of commonly used constraints. These are foremost theconstraints defined by the Bean Validation specification (seeTable 2.2, “Bean Validation constraints”).Additionally, Hibernate Validator provides useful custom constraints (seeTable 2.3, “Custom constraints” andTable 2.4, “Custom country specific constraints”).
Table 2.2, “Bean Validation constraints” shows purpose and supported data types of all constraints specified inthe Bean Validation API. All these constraints apply to the field/property level, there are noclass-level constraints defined in the Bean Validation specification. If you are using the Hibernateobject-relational mapper, some of the constraints are taken into account when creating the DDL foryour model (see column "Hibernate metadata impact").
Hibernate Validator allows some constraints to be applied to more data types than required by theBean Validation specification (e.g.@Max can be applied to strings). Relying on this feature canimpact portability of your application between Bean Validation providers.
Table 2.2. Bean Validation constraints
| Annotation | Supported data types | Use | Hibernate metadata impact |
|---|---|---|---|
|
| Checks that the annotated element is false | None |
|
| Checks that the annotated element is true | None |
|
| Checks whether the annotated value is less than the specified maximum, when inclusive=false. Otherwise whether the value is less than or equal to the specified maximum. The parameter value is the string representation of the max value according to the | None |
|
| Checks whether the annotated value is larger than the specified minimum, when inclusive=false. Otherwise whether the value is larger than or equal to the specified minimum. The parameter value is the string representation of the min value according to the | None |
| BigDecimal, | Checks whether the annotated value is a number having up to | Defines column precision and scale |
|
| Checks whether the annotated date is in the future | None |
|
| Checks whether the annotated value is less than or equal to the specified maximum | Adds a check constraint on the column |
|
| Checks whether the annotated value is higher than or equal to the specified minimum | Adds a check constraint on the column |
| Any type | Checks that the annotated value is not | Column(s) are not nullable |
| Any type | Checks that the annotated value is | None |
|
| Checks whether the annotated date is in the past | None |
|
| Checks if the annotated string matches the regular expression | None |
|
| Checks if the annotated element’s size is between | Column length will be set to |
| Any non-primitive type | Performs validation recursively on the associated object. If the object is a collection or an array, the elements are validated recursively. If the object is a map, the value elements are validated recursively. | None |
On top of the parameters indicated inTable 2.2, “Bean Validation constraints” each constraint has the parametersmessage, groups and payload. This is a requirement of the Bean Validation specification.
In addition to the constraints defined by the Bean Validation API Hibernate Validator providesseveral useful custom constraints which are listed inTable 2.3, “Custom constraints”. With oneexception also these constraints apply to the field/property level, only@ScriptAssert is a class-level constraint.
Table 2.3. Custom constraints
| Annotation | Supported data types | Use | Hibernate metadata impact |
|---|---|---|---|
|
| Checks that the annotated character sequence passes the Luhn checksum test. Note, this validation aims to check for user mistakes, not credit card validity! See alsoAnatomy of Credit Card Numbers. | None |
|
| Checks that the annotated character sequence is a validEAN barcode.type determines the type of barcode. The default is EAN-13. | None |
|
| Checks whether the specified character sequence is a valid email address. The optional parameters | None |
|
| Validates that the annotated character sequence is between | Column length will be set to max |
|
| Checks that the digits within the annotated charactersequence pass the Luhn checksum algorithm (see alsoLuhn algorithm). | None |
|
| Checks that the digits within the annotated charactersequence pass the generic mod 10 checksum algorithm. | None |
|
| Checks that the digits within the annotated charactersequence pass the mod 11 checksum algorithm. | None |
|
| Checks that the annotated character sequence is not nulland the trimmed length is greater than 0. The difference to | None |
|
| Checks whether the annotated element is not null nor empty | None |
|
| Checks whether the annotated value lies between (inclusive) the specified minimum and maximum | None |
|
| Checks whether the annotated valuecontains potentially malicious fragments such as | None |
| Any type | Checks whether the given script can successfully beevaluated against the annotated element. In order to use thisconstraint, an implementation of the Java Scripting API asdefined by JSR 223 ("Scripting for theJavaTM Platform") must part of theclass path. The expressions to be evaluated can be written inany scripting or expression language, for which a JSR 223compatible engine can be found in the class path. | None |
|
| Checks if the annotated character sequence is a valid URLaccording to RFC2396. If any of the optional parameters | None |
Hibernate Validator offers also some country specific constraints, e.g. for the validation of socialsecurity numbers.
If you have to implement a country specific constraint, consider making it a contribution toHibernate Validator!
Table 2.4. Custom country specific constraints
| Annotation | Supported data types | Use | Country | Hibernate metadata impact |
|---|---|---|---|---|
|
| Checks that the annotated character sequence represents a Brazilian corporate tax payer registry number (Cadastro de Pessoa Juríeddica) | Brazil | None |
|
| Checks that the annotated character sequence represents a Brazilian individual taxpayer registry number (Cadastro de Pessoa Fídsica) | Brazil | None |
|
| Checks that the annotated character sequence represents a Brazilian voter ID card number (Título Eleitoral) | Brazil | None |
In some cases neither the Bean Validation constraints nor the custom constraints provided byHibernate Validator will fulfill your requirements. In this case you can easily write your ownconstraint. You can find more information inChapter 6,Creating custom constraints.
As of Bean Validation 1.1, constraints can not only be applied to JavaBeans and their properties,but also to the parameters and return values of the methods and constructors of any Java type. Thatway Bean Validation constraints can be used to specify
For the purpose of this reference guide, the termmethod constraint refers to both, method andconstructor constraints, if not stated otherwise. Occasionally, the termexecutable is used whenreferring to methods and constructors.
This approach has several advantages over traditional ways of checking the correctness of parametersand return values:
IllegalArgumentException orsimilar), resulting in less code to write and maintainIn order to make annotations show up in the JavaDoc of annotated elements, the annotation typesthemselves must be annotated with the meta annotation @Documented. This is the case for all built-inconstraints and is considered a best practice for any custom constraints.
In the remainder of this chapter you will learn how to declare parameter and return valueconstraints and how to validate them using theExecutableValidator API.
You specify the preconditions of a method or constructor by adding constraint annotations to itsparameters as demonstrated inExample 3.1, “Declaring method and constructor parameter constraints”.
Example 3.1. Declaring method and constructor parameter constraints
package org.hibernate.validator.referenceguide.chapter03.parameter;public class RentalStation {public RentalStation(@NotNull String name) {//...}public void rentCar(@NotNull Customer customer,@NotNull @Future Date startDate,@Min(1) int durationInDays) {//...}}The following preconditions are declared here:
name passed to theRentalCar constructor must not benullrentCar() method, the givencustomer must not benull, the rental’s startdate must not benull as well as be in the future and finally the rental duration must be at leastone dayNote that declaring method or constructor constraints itself does not automatically cause theirvalidation upon invocation of the executable. Instead, theExecutableValidator API (seeSection 3.2, “Validating method constraints”) must be used to perform the validation, which isoften done using a method interception facility such as AOP, proxy objects etc.
Constraints may only be applied to instance methods, i.e. declaring constraints on static methods isnot supported. Depending on the interception facility you use for triggering method validation,additional restrictions may apply, e.g. with respect to the visibility of methods supported astarget of interception. Refer to the documentation of the interception technology to find outwhether any such limitations exist.
Sometimes validation does not only depend on a single parameter but on several or even allparameters of a method or constructor. This kind of requirement can be fulfilled with help of across-parameter constraint.
Cross-parameter constraints can be considered as the method validation equivalent to class-levelconstraints. Both can be used to implement validation requirements which are based on severalelements. While class-level constraints apply to several properties of a bean, cross-parameterconstraints apply to several parameters of an executable.
In contrast to single-parameter constraints, cross-parameter constraints are declared on the methodor constructor as you can see inExample 3.2, “Declaring a cross-parameter constraint”. Here the cross-parameter constraint@LuggageCountMatchesPassengerCount declared on theload() method is used toensure that no passenger has more than two pieces of luggage.
Example 3.2. Declaring a cross-parameter constraint
package org.hibernate.validator.referenceguide.chapter03.crossparameter;public class Car {@LuggageCountMatchesPassengerCount(piecesOfLuggagePerPassenger = 2)public void load(List<Person> passengers, List<PieceOfLuggage> luggage) {//...}}As you will learn in the next section, return value constraints are also declared on the methodlevel. In order to distinguish cross-parameter constraints from return value constraints, theconstraint target is configured in theConstraintValidator implementation using the@SupportedValidationTarget annotation. You can find out about the details inSection 6.3, “Cross-parameter constraints” which shows how to implement your own cross-parameter constraint.
In some cases a constraint can be applied to an executable’s parameters (i.e. it is a cross-parameter constraint), but also to the return value. One example for this are custom constraintswhich allow to specify validation rules using expression or script languages.
Such constraints must define a membervalidationAppliesTo() which can be used at declaration time tospecify the constraint target. As shown inExample 3.3, “Specifying a constraint’s target” you apply theconstraint to an executable’s parameters by specifyingvalidationAppliesTo = ConstraintTarget.PARAMETERS, whileConstraintTarget.RETURN_VALUE is usedto apply the constraint to the executable return value.
Example 3.3. Specifying a constraint’s target
package org.hibernate.validator.referenceguide.chapter03.crossparameter.constrainttarget;public class Garage {@ELAssert(expression = "...", validationAppliesTo = ConstraintTarget.PARAMETERS)public Car buildCar(List<Part> parts) {//...}@ELAssert(expression = "...", validationAppliesTo = ConstraintTarget.RETURN_VALUE)public Car paintCar(int color) {//...}}Although such a constraint is applicable to the parameters and return value of an executable, thetarget can often be inferred automatically. This is the case, if the constraint is declared on
In these situations you don’t have to specify the constraint target. It is still recommended to doso if it increases readability of the source code. If the constraint target is not specified insituations where it can’t be determined automatically, a ConstraintDeclarationException is raised.
The postconditions of a method or constructor are declared by adding constraint annotations to theexecutable as shown inExample 3.4, “Declaring method and constructor return value constraints”.
Example 3.4. Declaring method and constructor return value constraints
package org.hibernate.validator.referenceguide.chapter03.returnvalue;public class RentalStation {@ValidRentalStationpublic RentalStation() {//...}@NotNull@Size(min = 1)public List<Customer> getCustomers() {//...}}The following constraints apply to the executables of RentalStation:
RentalStation object must satisfy the@ValidRentalStation constraintgetCustomers() must not benull and must contain at least on elementSimilar to the cascaded validation of JavaBeans properties (seeSection 2.1.6, “Object graphs”), the@Valid annotation can be used to mark executableparameters and return values for cascaded validation. When validating a parameter or return valueannotated with@Valid, the constraints declared on the parameter or return value object arevalidated as well.
InExample 3.5, “Marking executable parameters and return values for cascaded validation”, thecar parameter of the methodGarage#checkCar() aswell as the return value of theGarage constructor are marked for cascaded validation.
Example 3.5. Marking executable parameters and return values for cascaded validation
package org.hibernate.validator.referenceguide.chapter03.cascaded;public class Garage {@NotNullprivate String name;@Validpublic Garage(String name) {this.name = name;}public boolean checkCar(@Valid @NotNull Car car) {//...}}package org.hibernate.validator.referenceguide.chapter03.cascaded;public class Car {@NotNullprivate String manufacturer;@NotNull@Size(min = 2, max = 14)private String licensePlate;public Car(String manufacturer, String licencePlate) {this.manufacturer = manufacturer;this.licensePlate = licencePlate;}//getters and setters ...}When validating the arguments of thecheckCar() method, the constraints on the properties of thepassedCar object are evaluated as well. Similarly, the@NotNull constraint on the name field ofGarage is checked when validating the return value of theGarage constructor.
Generally, the cascaded validation works for executables in exactly the same way as it does forJavaBeans properties.
In particular,null values are ignored during cascaded validation (naturally this can’t happenduring constructor return value validation) and cascaded validation is performed recursively, i.e.if a parameter or return value object which is marked for cascaded validation itself has propertiesmarked with@Valid, the constraints declared on the referenced elements will be validated as well.
Cascaded validation can not only be applied to simple object references but also to collection-typedparameters and return values. This means when putting the@Valid annotation to a parameter or returnvalue which
java.lang.Iterablejava.util.Mapeach contained element gets validated. So when validating the arguments of thecheckCars() method inExample 3.6, “List-typed method parameter marked for cascaded validation”, each element instance of the passed list willbe validated and aConstraintViolation created when any of the containedCar instances is invalid.
Example 3.6. List-typed method parameter marked for cascaded validation
package org.hibernate.validator.referenceguide.chapter03.cascaded.collection;public class Garage {public boolean checkCars(@Valid @NotNull List<Car> cars) {//...}}When declaring method constraints in inheritance hierarchies, it is important to be aware of thefollowing rules:
These rules are motivated by the concept ofbehavioral subtyping which requires that wherever atypeT is used, also a subtypeS ofT may be used without altering the program’s behavior.
As an example, consider a class invoking a method on an object with the static typeT. If theruntime type of that object wasS andS imposed additional preconditions, the client class mightfail to satisfy these preconditions as is not aware of them. The rules of behavioral subtyping arealso known as theLiskovsubstitution principle.
The Bean Validation specification implements the first rule by disallowing parameter constraints onmethods which override or implement a method declared in a supertype (superclass or interface).Example 3.7, “Illegal method parameter constraint in subtype” shows a violation of this rule.
Example 3.7. Illegal method parameter constraint in subtype
package org.hibernate.validator.referenceguide.chapter03.inheritance.parameter;public interface Vehicle { void drive(@Max(75) int speedInMph);}package org.hibernate.validator.referenceguide.chapter03.inheritance.parameter;public class Car implements Vehicle {@Overridepublic void drive(@Max(55) int speedInMph) {//...}}The@Max constraint onCar#drive() is illegal since this method implements the interface methodVehicle#drive(). Note that parameter constraints on overriding methods are also disallowed, if thesupertype method itself doesn’t declare any parameter constraints.
Furthermore, if a method overrides or implements a method declared in several parallel supertypes(e.g. two interfaces not extending each other or a class and an interface not implemented by thatclass), no parameter constraints may be specified for the method in any of the involved types. Thetypes inExample 3.8, “Illegal method parameter constraint in parallel types of a hierarchy” demonstrate a violation of thatrule. The methodRacingCar#drive() overridesVehicle#drive() as well asCar#drive().Therefore the constraint onVehicle#drive() is illegal.
Example 3.8. Illegal method parameter constraint in parallel types of a hierarchy
package org.hibernate.validator.referenceguide.chapter03.inheritance.parallel;public interface Vehicle {void drive(@Max(75) int speedInMph);}package org.hibernate.validator.referenceguide.chapter03.inheritance.parallel;public interface Car {public void drive(int speedInMph);}package org.hibernate.validator.referenceguide.chapter03.inheritance.parallel;public class RacingCar implements Car, Vehicle {@Overridepublic void drive(int speedInMph) {//...}}The previously described restrictions only apply to parameter constraints. In contrast, return valueconstraints may be added in methods overriding or implementing any supertype methods.
In this case, all the method’s return value constraints apply for the subtype method, i.e. theconstraints declared on the subtype method itself as well as any return value constraints onoverridden/implemented supertype methods. This is legal as putting additional return valueconstraints in place may never represent a weakening of the postconditions guaranteed to the callerof a method.
So when validating the return value of the methodCar#getPassengers() shown inExample 3.9, “Return value constraints on supertype and subtype method”, the@Size constraint on the method itself as wellas the@NotNull constraint on the implemented interface methodVehicle#getPassengers() apply.
Example 3.9. Return value constraints on supertype and subtype method
package org.hibernate.validator.referenceguide.chapter03.inheritance.returnvalue;public interface Vehicle {@NotNullList<Person> getPassengers();}package org.hibernate.validator.referenceguide.chapter03.inheritance.returnvalue;public class Car implements Vehicle {@Override@Size(min = 1)public List<Person> getPassengers() {//...}}If the validation engine detects a violation of any of the aforementioned rules, aConstraintDeclarationException will be raised.
The rules described in this section only apply to methods but not constructors. By definition,constructors never override supertype constructors. Therefore, when validating the parameters or thereturn value of a constructor invocation only the constraints declared on the constructor itselfapply, but never any constraints declared on supertype constructors.
The validation of method constraints is done using theExecutableValidator interface.
InSection 3.2.1, “Obtaining anExecutableValidator instance” you will learn how to obtain anExecutableValidatorinstance whileSection 3.2.2, “ExecutableValidator methods” shows how to use the different methodsoffered by this interface.
Instead of calling theExecutableValidator methods directly from within application code, they areusually invoked via a method interception technology such as AOP, proxy objects, etc. This causesexecutable constraints to be validated automatically and transparently upon method or constructorinvocation. Typically aConstraintViolationException is raised by the integration layer in case anyof the constraints is violated.
You can retrieve anExecutableValidator instance viaValidator#forExecutables() as shown inExample 3.10, “Obtaining anExecutableValidator instance”.
Example 3.10. Obtaining anExecutableValidator instance
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();executableValidator = factory.getValidator().forExecutables();In the example the executable validator is retrieved from the default validator factory, but ifrequired you could also bootstrap a specifically configured factory as described inChapter 8,Bootstrapping, for instance in order to use a specific parameter name provider(seeSection 8.2.4, “ParameterNameProvider”).
TheExecutableValidator interface offers altogether four methods:
validateParameters() andvalidateReturnValue() for method validationvalidateConstructorParameters() andvalidateConstructorReturnValue() for constructor validationJust as the methods onValidator, all these methods return aSet<ConstraintViolation> which containsaConstraintViolation instance for each violated constraint and which is empty if the validationsucceeds. Also all the methods have a var-args groups parameter by which you can pass the validationgroups to be considered for validation.
The examples in the following sections are based on the methods on constructors of theCar classshown inExample 3.11, “ClassCar with constrained methods and constructors”.
Example 3.11. ClassCar with constrained methods and constructors
package org.hibernate.validator.referenceguide.chapter03.validation;public class Car {public Car(@NotNull String manufacturer) {//...}@ValidRacingCarpublic Car(String manufacturer, String team) {//...}public void drive(@Max(75) int speedInMph) {//...}@Size(min = 1)public List<Passenger> getPassengers() {//...}}The methodvalidateParameters() is used to validate the arguments of a method invocation.Example 3.12, “UsingExecutableValidator#validateParameters()” shows an example. The validation results in aviolation of the@Max constraint on the parameter of thedrive() method.
Example 3.12. UsingExecutableValidator#validateParameters()
Car object = new Car( "Morris" );Method method = Car.class.getMethod( "drive", int.class );Object[] parameterValues = { 80 };Set<ConstraintViolation<Car>> violations = executableValidator.validateParameters(object,method,parameterValues);assertEquals( 1, violations.size() );Class<? extends Annotation> constraintType = violations.iterator().next().getConstraintDescriptor().getAnnotation().annotationType();assertEquals( Max.class, constraintType );Note thatvalidateParameters() validates all the parameter constraints of a method, i.e. constraintson individual parameters as well as cross-parameter constraints.
UsingvalidateReturnValue() the return value of a method can can be validated. The validation inExample 3.13, “UsingExecutableValidator#validateReturnValue()” yields one constraint violation since thegetPassengers() method is expect to return at least onePassenger instance.
Example 3.13. UsingExecutableValidator#validateReturnValue()
Car object = new Car( "Morris" );Method method = Car.class.getMethod( "getPassengers" );Object returnValue = Collections.<Passenger>emptyList();Set<ConstraintViolation<Car>> violations = executableValidator.validateReturnValue(object,method,returnValue);assertEquals( 1, violations.size() );Class<? extends Annotation> constraintType = violations.iterator().next().getConstraintDescriptor().getAnnotation().annotationType();assertEquals( Size.class, constraintType );The arguments of constructor invocations can be validated withvalidateConstructorParameters() asshown in methodExample 3.14, “UsingExecutableValidator#validateConstructorParameters()”. Due to the@NotNull constraint on the manufacturer parameter, the validation call returns one constraintviolation.
Example 3.14. UsingExecutableValidator#validateConstructorParameters()
Constructor<Car> constructor = Car.class.getConstructor( String.class );Object[] parameterValues = { null };Set<ConstraintViolation<Car>> violations = executableValidator.validateConstructorParameters(constructor,parameterValues);assertEquals( 1, violations.size() );Class<? extends Annotation> constraintType = violations.iterator().next().getConstraintDescriptor().getAnnotation().annotationType();assertEquals( NotNull.class, constraintType );Finally, by usingvalidateConstructorReturnValue() you can validate a constructor’s return value. InExample 3.15, “UsingExecutableValidator#validateConstructorReturnValue()”,validateConstructorReturnValue()returns one constraint violation, since theCar instance returned by the constructor doesn’t satisfythe@ValidRacingCar constraint (not shown).
Example 3.15. UsingExecutableValidator#validateConstructorReturnValue()
//constructor for creating racing carsConstructor<Car> constructor = Car.class.getConstructor( String.class, String.class );Car createdObject = new Car( "Morris", null );Set<ConstraintViolation<Car>> violations = executableValidator.validateConstructorReturnValue(constructor,createdObject);assertEquals( 1, violations.size() );Class<? extends Annotation> constraintType = violations.iterator().next().getConstraintDescriptor().getAnnotation().annotationType();assertEquals( ValidRacingCar.class, constraintType );In addition to the methods introduced inSection 2.2.3, “ConstraintViolation methods”,ConstraintViolation provides two more methods specific to the validation of executable parametersand return values.
ConstraintViolation#getExecutableParameters() returns the validated parameter array in case ofmethod or constructor parameter validation, whileConstraintViolation#getExecutableReturnValue()provides access to the validated object in case of return value validation.
All the otherConstraintViolation methods generally work for method validation in the same way asfor validation of beans. Refer to theJavaDoc to learn more about thebehavior of the individual methods and their return values during bean and method validation.
Note thatgetPropertyPath() can be very useful in order to obtain detailed information about thevalidated parameter or return value, e.g. for logging purposes. In particular, you can retrieve nameand argument types of the concerned method as well as the index of the concerned parameter from thepath nodes. How this can be done is shown inExample 3.16, “Retrieving method and parameter information”.
Example 3.16. Retrieving method and parameter information
Car object = new Car( "Morris" );Method method = Car.class.getMethod( "drive", int.class );Object[] parameterValues = { 80 };Set<ConstraintViolation<Car>> violations = executableValidator.validateParameters(object,method,parameterValues);assertEquals( 1, violations.size() );Iterator<Node> propertyPath = violations.iterator().next().getPropertyPath().iterator();MethodNode methodNode = propertyPath.next().as( MethodNode.class );assertEquals( "drive", methodNode.getName() );assertEquals( Arrays.<Class<?>>asList( int.class ), methodNode.getParameterTypes() );ParameterNode parameterNode = propertyPath.next().as( ParameterNode.class );assertEquals( "arg0", parameterNode.getName() );assertEquals( 0, parameterNode.getParameterIndex() );The parameter name is determined using the currentParameterNameProvider (seeSection 8.2.4, “ParameterNameProvider”) and defaults toarg0,arg1 etc.
In addition to the built-in bean and property-level constraints discussed inSection 2.3, “Built-in constraints”, Hibernate Validator currently provides one method-level constraint,@ParameterScriptAssert. This is a generic cross-parameter constraint which allows to implementvalidation routines using any JSR 223 compatible ("Scripting for the JavaTM Platform") scriptinglanguage, provided an engine for this language is available on the classpath.
To refer to the executable’s parameters from within the expression, use their name as obtained fromthe active parameter name provider (seeSection 8.2.4, “ParameterNameProvider”).Example 3.17, “Using@ParameterScriptAssert” shows how the validation logic of the@LuggageCountMatchesPassengerCountconstraint fromExample 3.2, “Declaring a cross-parameter constraint” could be expressed with the help of@ParameterScriptAssert.
Example 3.17. Using@ParameterScriptAssert
package org.hibernate.validator.referenceguide.chapter03.parametersscriptassert;public class Car {@ParameterScriptAssert(lang = "javascript", script = "arg1.size() <= arg0.size() * 2")public void load(List<Person> passengers, List<PieceOfLuggage> luggage) {//...}}Message interpolation is the process of creating error messages for violated Bean Validationconstraints. In this chapter you will learn how such messages are defined and resolved and how youcan plug in custom message interpolators in case the default algorithm is not sufficient for yourrequirements.
Constraint violation messages are retrieved from so called message descriptors. Each constraintdefines its default message descriptor using the message attribute. At declaration time, the defaultdescriptor can be overridden with a specific value as shown inExample 4.1, “Specifying a message descriptor using the message attribute”.
Example 4.1. Specifying a message descriptor using the message attribute
package org.hibernate.validator.referenceguide.chapter04;public class Car {@NotNull(message = "The manufacturer name must not be null")private String manufacturer;//constructor, getters and setters ...}If a constraint is violated, its descriptor will be interpolated by the validation engine using thecurrently configuredMessageInterpolator. The interpolated error message can then be retrieved fromthe resulting constraint violation by callingConstraintViolation#getMessage().
Message descriptors can containmessage parameters as well asmessage expressions which will beresolved during interpolation. Message parameters are string literals enclosed in{}, whilemessage expressions are string literals enclosed in${}. The following algorithm is applied duringmethod interpolation:
Locale#getDefault()) will be used when looking up messages in the bundle.org.hibernate.validator.ValidationMessages. If this step triggers a replacement, step 1 is executedagain, otherwise step 3 is applied.Size#min()) inthe error message (e.g. "must be at least ${min}").You can find the formal definition of the interpolation algorithm in section5.3.1.1 of the BeanValidation specification.
Since the characters{,} and$ have a special meaning in message descriptors they need to be escaped if you want to use them literally. The following rules apply:
\{ is considered as the literal{\} is considered as the literal}\$ is considered as the literal$\\ is considered as the literal\As of Hibernate Validator 5 (Bean Validation 1.1) it is possible to use the Unified ExpressionLanguage (as defined byJSR 341) in constraintviolation messages. This allows to define error messages based on conditional logic and also enablesadvanced formatting options. The validation engine makes the following objects available in the ELcontext:
format(String format, Object… args) which behaves likejava.util.Formatter.format(String format, Object… args).The following section provides several examples for using EL expressions in error messages.
Example 4.2, “Specifying message descriptors” shows how to make use of the different options for specifyingmessage descriptors.
Example 4.2. Specifying message descriptors
package org.hibernate.validator.referenceguide.chapter04.complete;public class Car {@NotNullprivate String manufacturer;@Size(min = 2,max = 14,message = "The license plate '${validatedValue}' must be between {min} and {max} characters long")private String licensePlate;@Min(value = 2,message = "There must be at least {value} seat${value > 1 ? 's' : ''}")private int seatCount;@DecimalMax(value = "350",message = "The top speed ${formatter.format('%1$.2f', validatedValue)} is higher " +"than {value}")private double topSpeed;@DecimalMax(value = "100000", message = "Price must not be higher than ${value}")private BigDecimal price;public Car(String manufacturer,String licensePlate,int seatCount,double topSpeed,BigDecimal price) {this.manufacturer = manufacturer;this.licensePlate = licensePlate;this.seatCount = seatCount;this.topSpeed = topSpeed;this.price = price;}//getters and setters ...}Validating an invalidCar instance yields constraint violations with the messages shown by theassertions inExample 4.3, “Expected error messages”:
@NotNull constraint on themanufacturer field causes the error message "may not be null", asthis is the default message defined by the Bean Validation specification and no specific descriptoris given in the message attribute@Size constraint on thelicensePlate field shows the interpolation of message parameters({min},{max}) and how to add the validated value to the error message using the ELexpression${validatedValue}@Min constraint onseatCount demonstrates how use an EL expression with a ternery expression todynamically chose singular or plural form, depending on an attribute of the constraint ("There mustbe at least 1 seat" vs. "There must be at least 2 seats")@DecimalMax constraint ontopSpeed shows how to format the validatedvalue using the formatter instance@DecimalMax constraint on price shows that parameter interpolation has precedence overexpression evaluation, causing the$ sign to show up in front of the maximum priceOnly actual constraint attributes can be interpolated using message parameters in the form{attributeName}. When referring to the validated value or custom expression variables added to theinterpolation context (seeSection 11.9.1, “HibernateConstraintValidatorContext”), an EL expression in theform${attributeName} must be used.
Example 4.3. Expected error messages
Car car = new Car( null, "A", 1, 400.123456, BigDecimal.valueOf( 200000 ) );String message = validator.validateProperty( car, "manufacturer" ).iterator().next().getMessage();assertEquals( "may not be null", message );message = validator.validateProperty( car, "licensePlate" ).iterator().next().getMessage();assertEquals("The license plate must be between 2 and 14 characters long",message);message = validator.validateProperty( car, "seatCount" ).iterator().next().getMessage();assertEquals( "There must be at least 2 seats", message );message = validator.validateProperty( car, "topSpeed" ).iterator().next().getMessage();assertEquals( "The top speed 400.12 is higher than 350", message );message = validator.validateProperty( car, "price" ).iterator().next().getMessage();assertEquals( "Price must not be higher than $100000", message );If the default message interpolation algorithm does not fit your requirements it is also possible toplug in a customMessageInterpolator implementation.
Custom interpolators must implement the interfacejavax.validation.MessageInterpolator. Note thatimplementations must be thread-safe. It is recommended that custom message interpolators delegatefinal implementation to the default interpolator, which can be obtained viaConfiguration#getDefaultMessageInterpolator().
In order to use a custom message interpolator it must be registered either by configuring it in theBean Validation XML descriptorMETA-INF/validation.xml (seeSection 7.1, “Configuring the validator factory invalidation.xml”) or by passing it when bootstrapping aValidatorFactory orValidator (seeSection 8.2.1, “MessageInterpolator” andSection 8.3, “Configuring a Validator”, respectively).
In some use cases you want to use the message interpolation algorithm as defined by the BeanValidation specification, but retrieve error messages from other resource bundles thanValidationMessages. In this situation Hibernate Validator’sResourceBundleLocator SPI can help.
The default message interpolator in Hibernate Validator,ResourceBundleMessageInterpolator,delegates retrieval of resource bundles to that SPI. Using an alternative bundle only requirespassing an instance ofPlatformResourceBundleLocator with the bundle name when bootstrapping theValidatorFactory as shown inExample 4.4, “Using a specific resource bundle”.
Example 4.4. Using a specific resource bundle
Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(new ResourceBundleMessageInterpolator(new PlatformResourceBundleLocator( "MyMessages" ))).buildValidatorFactory().getValidator();Of course you also could implement a completely differentResourceBundleLocator, which for instancereturns bundles backed by records in a database. In this case you can obtain the default locator viaHibernateValidatorConfiguration#getDefaultResourceBundleLocator(), which you e.g. could use asfall-back for your custom locator.
BesidesPlatformResourceBundleLocator, Hibernate Validator provides another resource bundle locatorimplementation out of the box, namelyAggregateResourceBundleLocator, which allows to retrieve errormessages from more than one resource bundle. You could for instance use this implementation in amulti-module application where you want to have one message bundle per module.Example 4.5, “UsingAggregateResourceBundleLocator” shows how to useAggregateResourceBundleLocator.
Example 4.5. UsingAggregateResourceBundleLocator
Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(new ResourceBundleMessageInterpolator(new AggregateResourceBundleLocator(Arrays.asList("MyMessages","MyOtherMessages")))).buildValidatorFactory().getValidator();Note that the bundles are processed in the order as passed to the constructor. That means if severalbundles contain an entry for a given message key, the value will be taken from the first bundle inthe list containing the key.
All validation methods onValidator andExecutableValidator discussed in earlier chapters also takea var-arg argument groups. So far we have been ignoring this parameter, but it is time to have acloser look.
Groups allow you to restrict the set of constraints applied during validation. One use case forvalidation groups are UI wizards where in each step only a specified subset of constraints shouldget validated. The groups targeted are passed as var-arg parameters to the appropriate validatemethod.
Let’s have a look at an example. The classPerson inExample 5.1, “Example classPerson” has a@NotNullconstraint onname. Since no group is specified for this annotation the default groupjavax.validation.groups.Default is assumed.
When more than one group is requested, the order in which the groups are evaluated is notdeterministic. If no group is specified the default groupjavax.validation.groups.Default isassumed.
Example 5.1. Example classPerson
package org.hibernate.validator.referenceguide.chapter05;public class Person {@NotNullprivate String name;public Person(String name) {this.name = name;}// getters and setters ...}The classDriver inExample 5.2, “Driver” extendsPerson and adds the propertiesage andhasDrivingLicense. Drivers must be at least 18 years old (@Min(18)) and have a driving license(@AssertTrue). Both constraints defined on these properties belong to the groupDriverChecks whichis just a simple tagging interface.
Using interfaces makes the usage of groups type-safe and allows for easy refactoring. It also meansthat groups can inherit from each other via class inheritance.
Example 5.2. Driver
package org.hibernate.validator.referenceguide.chapter05;public class Driver extends Person {@Min(value = 18,message = "You have to be 18 to drive a car",groups = DriverChecks.class)public int age;@AssertTrue(message = "You first have to pass the driving test",groups = DriverChecks.class)public boolean hasDrivingLicense;public Driver(String name) {super( name );}public void passedDrivingTest(boolean b) {hasDrivingLicense = b;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}package org.hibernate.validator.referenceguide.chapter05;public interface DriverChecks {}Finally the classCar (Example 5.3, “Car”) has some constraints which are part of the default group aswell as@AssertTrue in the groupCarChecks on the propertypassedVehicleInspection which indicateswhether a car passed the road worthy tests.
Example 5.3. Car
package org.hibernate.validator.referenceguide.chapter05;public class Car {@NotNullprivate String manufacturer;@NotNull@Size(min = 2, max = 14)private String licensePlate;@Min(2)private int seatCount;@AssertTrue(message = "The car has to pass the vehicle inspection first",groups = CarChecks.class)private boolean passedVehicleInspection;@Validprivate Driver driver;public Car(String manufacturer, String licencePlate, int seatCount) {this.manufacturer = manufacturer;this.licensePlate = licencePlate;this.seatCount = seatCount;}// getters and setters ...}package org.hibernate.validator.referenceguide.chapter05;public interface CarChecks {}Overall three different groups are used in the example:
Person.name,Car.manufacturer,Car.licensePlate andCar.seatCountall belong to theDefault groupDriver.age andDriver.hasDrivingLicense belong toDriverChecksCar.passedVehicleInspection belongs to the groupCarChecksExample 5.4, “Using validation groups” shows how passing different group combinations to theValidator#validate()method results in different validation results.
Example 5.4. Using validation groups
// create a car and check that everything is ok with it.Car car = new Car( "Morris", "DD-AB-123", 2 );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 0, constraintViolations.size() );// but has it passed the vehicle inspection?constraintViolations = validator.validate( car, CarChecks.class );assertEquals( 1, constraintViolations.size() );assertEquals("The car has to pass the vehicle inspection first",constraintViolations.iterator().next().getMessage());// let's go to the vehicle inspectioncar.setPassedVehicleInspection( true );assertEquals( 0, validator.validate( car ).size() );// now let's add a driver. He is 18, but has not passed the driving test yetDriver john = new Driver( "John Doe" );john.setAge( 18 );car.setDriver( john );constraintViolations = validator.validate( car, DriverChecks.class );assertEquals( 1, constraintViolations.size() );assertEquals("You first have to pass the driving test",constraintViolations.iterator().next().getMessage());// ok, John passes the testjohn.passedDrivingTest( true );assertEquals( 0, validator.validate( car, DriverChecks.class ).size() );// just checking that everything is in order nowassertEquals(0, validator.validate(car,Default.class,CarChecks.class,DriverChecks.class).size());The firstvalidate() call inExample 5.4, “Using validation groups” is done using no explicit group. There are novalidation errors, even though the propertypassedVehicleInspection is per defaultfalse. However,the constraint defined on this property does not belong to the default group.
The next validation using theCarChecks group fails until the car passes the vehicle inspection.Adding a driver to the car and validating againstDriverChecks again yields one constraint violationdue to the fact that the driver has not yet passed the driving test. Only after settingpassedDrivingTest totrue the validation againstDriverChecks passes.
The lastvalidate() call finally shows that all constraints are passing by validating against alldefined groups.
By default, constraints are evaluated in no particular order, regardless of which groups they belongto. In some situations, however, it is useful to control the order constraints are evaluated.
In the example fromExample 5.4, “Using validation groups” it could for instance be required that first all defaultcar constraints are passing before checking the road worthiness of the car. Finally, before drivingaway, the actual driver constraints should be checked.
In order to implement such a validation order you just need to define an interface and annotate itwith@GroupSequence, defining the order in which the groups have to be validated (seeExample 5.5, “Defining a group sequence”). If at least one constraint fails in a sequenced group none of theconstraints of the following groups in the sequence get validated.
Example 5.5. Defining a group sequence
package org.hibernate.validator.referenceguide.chapter05;@GroupSequence({ Default.class, CarChecks.class, DriverChecks.class })public interface OrderedChecks {}Groups defining a sequence and groups composing a sequence must not be involved in a cyclicdependency either directly or indirectly, either through cascaded sequence definition or groupinheritance. If a group containing such a circularity is evaluated, aGroupDefinitionException israised.
You then can use the new sequence as shown in inExample 5.6, “Using a group sequence”.
Example 5.6. Using a group sequence
Car car = new Car( "Morris", "DD-AB-123", 2 );car.setPassedVehicleInspection( true );Driver john = new Driver( "John Doe" );john.setAge( 18 );john.passedDrivingTest( true );car.setDriver( john );assertEquals( 0, validator.validate( car, OrderedChecks.class ).size() );Besides defining group sequences, the@GroupSequence annotation also allows to redefine the defaultgroup for a given class. To do so, just add the@GroupSequence annotation to the class and specifythe sequence of groups which substitute Default for this class within the annotation.
Example 5.7, “ClassRentalCar with redefined default group” introduces a new classRentalCar with a redefined default group.
Example 5.7. ClassRentalCar with redefined default group
package org.hibernate.validator.referenceguide.chapter05;@GroupSequence({ RentalChecks.class, CarChecks.class, RentalCar.class })public class RentalCar extends Car {@AssertFalse(message = "The car is currently rented out", groups = RentalChecks.class)private boolean rented;public RentalCar(String manufacturer, String licencePlate, int seatCount) {super( manufacturer, licencePlate, seatCount );}public boolean isRented() {return rented;}public void setRented(boolean rented) {this.rented = rented;}}package org.hibernate.validator.referenceguide.chapter05;public interface RentalChecks {}With this definition you can evaluate the constraints belonging toRentalChecks,CarChecks andRentalCar by just requesting theDefault group as seen inExample 5.8, “Validating an object with redefined default group”.
Example 5.8. Validating an object with redefined default group
RentalCar rentalCar = new RentalCar( "Morris", "DD-AB-123", 2 );rentalCar.setPassedVehicleInspection( true );rentalCar.setRented( true );Set<ConstraintViolation<RentalCar>> constraintViolations = validator.validate( rentalCar );assertEquals( 1, constraintViolations.size() );assertEquals("Wrong message","The car is currently rented out",constraintViolations.iterator().next().getMessage());rentalCar.setRented( false );constraintViolations = validator.validate( rentalCar );assertEquals( 0, constraintViolations.size() );Since there must no cyclic dependency in the group and group sequence definitions one cannot justaddDefault to the sequence redefiningDefault for a class. Instead the class itself has to beadded!
TheDefault group sequence overriding is local to the class it is defined on and is not propagatedto associated objects. For the example this means that addingDriverChecks to the default groupsequence ofRentalCar would not have any effects. Only the groupDefault will be propagated to thedriver association.
Note that you can control the propagated group(s) by declaring a group conversion rule (seeSection 5.4, “Group conversion”).
In addition to statically redefining default group sequences via@GroupSequence, Hibernate Validatoralso provides an SPI for the dynamic redefinition of default group sequences depending on the objectstate.
For that purpose you need to implement the interfaceDefaultGroupSequenceProvider and register thisimplementation with the target class via the@GroupSequenceProvider annotation. In the rental carscenario you could for instance dynamically add theCarChecks as seen inExample 5.9, “Implementing and using a default group sequence provider”.
Example 5.9. Implementing and using a default group sequence provider
package org.hibernate.validator.referenceguide.chapter05.groupsequenceprovider;public class RentalCarGroupSequenceProviderimplements DefaultGroupSequenceProvider<RentalCar> {@Overridepublic List<Class<?>> getValidationGroups(RentalCar car) {List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();defaultGroupSequence.add( RentalCar.class );if ( car != null && !car.isRented() ) {defaultGroupSequence.add( CarChecks.class );}return defaultGroupSequence;}}package org.hibernate.validator.referenceguide.chapter05.groupsequenceprovider;@GroupSequenceProvider(RentalCarGroupSequenceProvider.class)public class RentalCar extends Car {@AssertFalse(message = "The car is currently rented out", groups = RentalChecks.class)private boolean rented;public RentalCar(String manufacturer, String licencePlate, int seatCount) {super( manufacturer, licencePlate, seatCount );}public boolean isRented() {return rented;}public void setRented(boolean rented) {this.rented = rented;}}What if you wanted to validate the car related checks together with the driver checks? Of course youcould pass the required groups to the validate call explicitly, but what if you wanted to make thesevalidations occur as part of theDefault group validation? Here@ConvertGroup comes into play whichallows you during cascaded validation to use a different group than the originally requested one.
Let’s have a look atExample 5.10, “@ConvertGroup usage”. Here@GroupSequence({CarChecks.class, Car.class }) is used to combine the car related constraints under theDefault group(seeSection 5.3, “Redefining the default group sequence”). There is also a@ConvertGroup(from = Default.class, to =DriverChecks.class) which ensures theDefault group gets converted to theDriverChecks group duringcascaded validation of the driver association.
Example 5.10. @ConvertGroup usage
package org.hibernate.validator.referenceguide.chapter05.groupconversion;public class Driver {@NotNullprivate String name;@Min(value = 18,message = "You have to be 18 to drive a car",groups = DriverChecks.class)public int age;@AssertTrue(message = "You first have to pass the driving test",groups = DriverChecks.class)public boolean hasDrivingLicense;public Driver(String name) {this.name = name;}public void passedDrivingTest(boolean b) {hasDrivingLicense = b;}// getters and setters ...}package org.hibernate.validator.referenceguide.chapter05.groupconversion;@GroupSequence({ CarChecks.class, Car.class })public class Car {@NotNullprivate String manufacturer;@NotNull@Size(min = 2, max = 14)private String licensePlate;@Min(2)private int seatCount;@AssertTrue(message = "The car has to pass the vehicle inspection first",groups = CarChecks.class)private boolean passedVehicleInspection;@Valid@ConvertGroup(from = Default.class, to = DriverChecks.class)private Driver driver;public Car(String manufacturer, String licencePlate, int seatCount) {this.manufacturer = manufacturer;this.licensePlate = licencePlate;this.seatCount = seatCount;}// getters and setters ...}As a result the validation inExample 5.11, “Test case for@ConvertGroup” succeeds, even though the constraintonhasDrivingLicense belongs to theDriverChecks group and only theDefault group is requested inthevalidate() call.
Example 5.11. Test case for@ConvertGroup
// create a car and validate. The Driver is still null and does not get validatedCar car = new Car( "VW", "USD-123", 4 );car.setPassedVehicleInspection( true );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 0, constraintViolations.size() );// create a driver who has not passed the driving testDriver john = new Driver( "John Doe" );john.setAge( 18 );// now let's add a driver to the carcar.setDriver( john );constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals("The driver constraint should also be validated as part of the default group",constraintViolations.iterator().next().getMessage(),"You first have to pass the driving test");You can define group conversions wherever@Valid can be used, namely associations as well as methodand constructor parameters and return values. Multiple conversions can be specified using@ConvertGroup.List.
However, the following restrictions apply:
@ConvertGroup must only be used in combination with@Valid. If used without, aConstraintDeclarationException is thrown.ConstraintDeclarationException is raised.ConstraintDeclarationException israised in this situation.Rules are not executed recursively. The first matching conversion rule is used and subsequent rulesare ignored. For example if a set of@ConvertGroup declarations chains groupA toB andB toC, the groupA will be converted toB and not toC.
The Bean Validation API defines a whole set of standard constraint annotations such as@NotNull,@Size etc. In cases where these buit-in constraints are not sufficient, you cean easily createcustom constraints tailored to your specific validation requirements.
To create a custom constraint, the following three steps are required:
This section shows how to write a constraint annotation which can be used to ensure that a givenstring is either completely upper case or lower case. Later on this constraint will be applied tothelicensePlate field of theCar class fromChapter 1,Getting started to ensure, thatthe field is always an upper-case string.
The first thing needed is a way to express the two case modes. While you could useString constants,a better approach is using a Java 5 enum for that purpose:
Example 6.1. EnumCaseMode to express upper vs. lower case
package org.hibernate.validator.referenceguide.chapter06;public enum CaseMode {UPPER,LOWER;}The next step is to define the actual constraint annotation. If you’ve never designed an annotationbefore, this may look a bit scary, but actually it’s not that hard:
Example 6.2. Defining the@CheckCase constraint annotation
package org.hibernate.validator.referenceguide.chapter06;@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = CheckCaseValidator.class)@Documentedpublic @interface CheckCase {String message() default "{org.hibernate.validator.referenceguide.chapter06.CheckCase." +"message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };CaseMode value();@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })@Retention(RUNTIME)@Documented@interface List {CheckCase[] value();}}An annotation type is defined using the@interface keyword. All attributes of an annotation type aredeclared in a method-like manner. The specification of the Bean Validation API demands, that anyconstraint annotation defines
message that returns the default key for creating error messages in case theconstraint is violatedgroups that allows the specification of validation groups, to which this constraintbelongs (seeChapter 5,Grouping constraints). This must default to an empty array of type Class<?>.an attributepayload that can be used by clients of the Bean Validation API to assign custompayload objects to a constraint. This attribute is not used by the API itself. An example for acustom payload could be the definition of a severity:
public class Severity {public interface Info extends Payload {}public interface Error extends Payload {}}public class ContactDetails {@NotNull(message = "Name is mandatory", payload = Severity.Error.class)private String name;@NotNull(message = "Phone number not specified, but not mandatory",payload = Severity.Info.class)private String phoneNumber;// ...}Now a client can after the validation of aContactDetails instance access the severity of aconstraint usingConstraintViolation.getConstraintDescriptor().getPayload() and adjust its behaviordepending on the severity.
Besides these three mandatory attributes there is another one,value, allowing for the required casemode to be specified. The namevalue is a special one, which can be omitted when using theannotation, if it is the only attribute specified, as e.g. in@CheckCase(CaseMode.UPPER).
In addition, the constraint annotation is decorated with a couple of meta annotations:
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE}): Defines the supported target element typesfor the constraint.@CheckCase may be used on fields (element typeFIELD), JavaBeans properties aswell as method return values (METHOD) and method/constructor parameters (PARAMETER). The elementtypeANNOTATION_TYPE allows for the creation of composed constraints(seeSection 6.4, “Constraint composition”) based on@CheckCase.
When creating a class-level constraint (seeSection 2.1.4, “Class-level constraints”), the elementtypeTYPE would have to be used. Constraints targeting the return value of a constructor need tosupport the element typeCONSTRUCTOR. Cross-parameter constraints (seeSection 6.3, “Cross-parameter constraints”) which are used to validate all the parameters of a methodor constructor together, must supportMETHOD orCONSTRUCTOR, respectively.
@Retention(RUNTIME): Specifies, that annotations of this type will be available at runtime by themeans of reflection@Constraint(validatedBy = CheckCaseValidator.class): Marks the annotation type as constraintannotation and specifies the validator to be used to validate elements annotated with@CheckCase.If a constraint may be used on several data types, several validators may be specified, one foreach data type.@Documented: Says, that the use of@CheckCase will be contained in the JavaDoc of elementsannotated with itFinally, there is an inner annotation type namedList. This annotation allows to specify several@CheckCase annotations on the same element, e.g. with different validation groups and messages.While also another name could be used, the Bean Validation specification recommends to use the nameList and make the annotation an inner annotation of the corresponding constraint type.
Having defined the annotation, you need to create a constraint validator, which is able to validateelements with a@CheckCase annotation. To do so, implement the interfaceConstraintValidator asshown below:
Example 6.3. Implementing a constraint validator for the constraint@CheckCase
package org.hibernate.validator.referenceguide.chapter06;public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {private CaseMode caseMode;@Overridepublic void initialize(CheckCase constraintAnnotation) {this.caseMode = constraintAnnotation.value();}@Overridepublic boolean isValid(String object, ConstraintValidatorContext constraintContext) {if ( object == null ) {return true;}if ( caseMode == CaseMode.UPPER ) {return object.equals( object.toUpperCase() );}else {return object.equals( object.toLowerCase() );}}}TheConstraintValidator interface defines two type parameters which are set in the implementation.The first one specifies the annotation type to be validated (CheckCase), the second one the type ofelements, which the validator can handle (String). In case a constraint supports several data types,aConstraintValidator for each allowed type has to be implemented and registered at the constraintannotation as shown above.
The implementation of the validator is straightforward. Theinitialize() method gives you access tothe attribute values of the validated constraint and allows you to store them in a field of thevalidator as shown in the example.
TheisValid() method contains the actual validation logic. For@CheckCase this is the check whethera given string is either completely lower case or upper case, depending on the case mode retrievedininitialize(). Note that the Bean Validation specification recommends to consider null values asbeing valid. Ifnull is not a valid value for an element, it should be annotated with@NotNullexplicitly.
Example 6.3, “Implementing a constraint validator for the constraint@CheckCase”relies on the default error message generation by just returningtrue orfalse from theisValid()method. Using the passedConstraintValidatorContext object it is possible to either add additionalerror messages or completely disable the default error message generation and solely define customerror messages. TheConstraintValidatorContext API is modeled as fluent interface and is bestdemonstrated with an example:
Example 6.4. UsingConstraintValidatorContext to define custom error messages
package org.hibernate.validator.referenceguide.chapter06.constraintvalidatorcontext;public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {private CaseMode caseMode;@Overridepublic void initialize(CheckCase constraintAnnotation) {this.caseMode = constraintAnnotation.value();}@Overridepublic boolean isValid(String object, ConstraintValidatorContext constraintContext) {if ( object == null ) {return true;}boolean isValid;if ( caseMode == CaseMode.UPPER ) {isValid = object.equals( object.toUpperCase() );}else {isValid = object.equals( object.toLowerCase() );}if ( !isValid ) {constraintContext.disableDefaultConstraintViolation();constraintContext.buildConstraintViolationWithTemplate("{org.hibernate.validator.referenceguide.chapter03." +"constraintvalidatorcontext.CheckCase.message}").addConstraintViolation();}return isValid;}}Example 6.4, “UsingConstraintValidatorContext to define custom error messages”shows how you can disable the default error message generation and add a custom error message usinga specified message template. In this example the use of theConstraintValidatorContext results inthe same error message as the default error message generation.
It is important to add each configured constraint violation by callingaddConstraintViolation().Only after that the new constraint violation will be created.
Refer toSection 6.2.1, “Custom property paths” to learn how to use theConstraintValidatorContext API tocontrol the property path of constraint violations for class-level constraints.
The last missing building block is an error message which should be used in case a@CheckCaseconstraint is violated. To define this, create a fileValidationMessages.properties with thefollowing contents (see alsoSection 4.1, “Default message interpolation”):
Example 6.5. Defining a custom error message for theCheckCase constraint
org.hibernate.validator.referenceguide.chapter06.CheckCase.message=Case mode must be {value}.If a validation error occurs, the validation runtime will use the default value, that you specifiedfor the message attribute of the@CheckCase annotation to look up the error message in this resourcebundle.
You can now use the constraint in theCar class from theChapter 1,Getting started chapter tospecify that thelicensePlate field should only contain upper-case strings:
Example 6.6. Applying the@CheckCase constraint
package org.hibernate.validator.referenceguide.chapter06;public class Car {@NotNullprivate String manufacturer;@NotNull@Size(min = 2, max = 14)@CheckCase(CaseMode.UPPER)private String licensePlate;@Min(2)private int seatCount;public Car ( String manufacturer, String licencePlate, int seatCount ) {this.manufacturer = manufacturer;this.licensePlate = licencePlate;this.seatCount = seatCount;}//getters and setters ...}Finally,Example 6.7, “Validating objects with the@CheckCase constraint” demonstrates how validating aCar instance with an invalidlicense plate causes the@CheckCase constraint to be violated.
Example 6.7. Validating objects with the@CheckCase constraint
//invalid license plateCar car = new Car( "Morris", "dd-ab-123", 4 );Set<ConstraintViolation<Car>> constraintViolations =validator.validate( car );assertEquals( 1, constraintViolations.size() );assertEquals("Case mode must be UPPER.",constraintViolations.iterator().next().getMessage());//valid license platecar = new Car( "Morris", "DD-AB-123", 4 );constraintViolations = validator.validate( car );assertEquals( 0, constraintViolations.size() );As discussed earlier, constraints can also be applied on the class level to validate the state of anentire object. Class-level constraints are defined in the same was as are property constraints.Example 6.8, “Implementing a class-level constraint” shows constraint annotation and validator of the@ValidPassengerCount constraint you already saw in use inExample 2.7, “Class-level constraint”.
Example 6.8. Implementing a class-level constraint
package org.hibernate.validator.referenceguide.chapter06.classlevel;@Target({ TYPE, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = { ValidPassengerCountValidator.class })@Documentedpublic @interface ValidPassengerCount {String message() default "{org.hibernate.validator.referenceguide.chapter06.classlevel." +"ValidPassengerCount.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };}package org.hibernate.validator.referenceguide.chapter06.classlevel;public class ValidPassengerCountValidatorimplements ConstraintValidator<ValidPassengerCount, Car> {@Overridepublic void initialize(ValidPassengerCount constraintAnnotation) {}@Overridepublic boolean isValid(Car car, ConstraintValidatorContext context) {if ( car == null ) {return true;}return car.getPassengers().size() <= car.getSeatCount();}}As the example demonstrates, you need to use the element typeTYPE in the@Target annotation. Thisallows the constraint to be put on type definitions. The validator of the constraint in the examplereceives aCar in theisValid() method and can access the complete object state to decide whetherthe given instance is valid or not.
By default the constraint violation for a class-level constraint is reported on the level of theannotated type, e.g.Car.
In some cases it is preferable though that the violation’s property path refers to one of theinvolved properties. For instance you might want to report the@ValidPassengerCount constraintagainst the passengers property instead of theCar bean.
Example 6.9, “Adding a newConstraintViolation with custom property path”shows how this can be done by using the constraint validator context passed toisValid() to build acustom constraint violation with a property node for the property passengers. Note that you alsocould add several property nodes, pointing to a sub-entity of the validated bean.
Example 6.9. Adding a newConstraintViolation with custom property path
package org.hibernate.validator.referenceguide.chapter06.custompath;public class ValidPassengerCountValidatorimplements ConstraintValidator<ValidPassengerCount, Car> {@Overridepublic void initialize(ValidPassengerCount constraintAnnotation) {}@Overridepublic boolean isValid(Car car, ConstraintValidatorContext constraintValidatorContext) {if ( car == null ) {return true;}boolean isValid = car.getPassengers().size() <= car.getSeatCount();if ( !isValid ) {constraintValidatorContext.disableDefaultConstraintViolation();constraintValidatorContext.buildConstraintViolationWithTemplate( "{my.custom.template}" ).addPropertyNode( "passengers" ).addConstraintViolation();}return isValid;}}Bean Validation distinguishes between two different kinds of constraints.
Generic constraints (which have been discussed so far) apply to the annotated element, e.g. a type,field, method parameter or return value etc. Cross-parameter constraints, in contrast, apply to thearray of parameters of a method or constructor and can be used to express validation logic whichdepends on several parameter values.
In order to define a cross-parameter constraint, its validator class must be annotated with@SupportedValidationTarget(ValidationTarget.PARAMETERS). The type parameterT from theConstraintValidator interface must resolve to eitherObject orObject[] in order to receive thearray of method/constructor arguments in theisValid() method.
The following example shows the definition of a cross-parameter constraint which can be used tocheck that twoDate parameters of a method are in the correct order:
Example 6.10. Cross-parameter constraint
package org.hibernate.validator.referenceguide.chapter06.crossparameter;@Constraint(validatedBy = ConsistentDateParameterValidator.class)@Target({ METHOD, CONSTRUCTOR, ANNOTATION_TYPE })@Retention(RUNTIME)@Documentedpublic @interface ConsistentDateParameters {String message() default "{org.hibernate.validator.referenceguide.chapter06." +"crossparameter.ConsistentDateParameters.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };}The definition of a cross-parameter constraint isn’t any different from defining a genericconstraint, i.e. it must specify the membersmessage(),groups() andpayload() and be annotated with@Constraint. This meta annotation also specifies the corresponding validator, which is shown inExample 6.11, “Generic and cross-parameter constraint”. Note that besides the element typesMETHOD andCONSTRUCTORalsoANNOTATION_TYPE is specified as target of the annotation, in order to enable the creation ofcomposed constraints based on@ConsistentDateParameters (seeSection 6.4, “Constraint composition”).
Cross-parameter constraints are specified directly on the declaration of a method or constructor,which is also the case for return value constraints. In order to improve code readability, it istherefore recommended to chose constraint names - such as@ConsistentDateParameters - which make theconstraint target apparent.
Example 6.11. Generic and cross-parameter constraint
package org.hibernate.validator.referenceguide.chapter06.crossparameter;@SupportedValidationTarget(ValidationTarget.PARAMETERS)public class ConsistentDateParameterValidator implementsConstraintValidator<ConsistentDateParameters, Object[]> {@Overridepublic void initialize(ConsistentDateParameters constraintAnnotation) {}@Overridepublic boolean isValid(Object[] value, ConstraintValidatorContext context) {if ( value.length != 2 ) {throw new IllegalArgumentException( "Illegal method signature" );}//leave null-checking to @NotNull on individual parametersif ( value[0] == null || value[1] == null ) {return true;}if ( !( value[0] instanceof Date ) || !( value[1] instanceof Date ) ) {throw new IllegalArgumentException("Illegal method signature, expected two " +"parameters of type Date.");}return ( (Date) value[0] ).before( (Date) value[1] );}}As discussed above, the validation targetPARAMETERS must be configured for a cross-parametervalidator by using the@SupportedValidationTarget annotation. Since a cross-parameter constraintcould be applied to any method or constructor, it is considered a best practice to check for theexpected number and types of parameters in the validator implementation.
As with generic constraints,null parameters should be considered valid and@NotNull on theindividual parameters should be used to make sure that parameters are notnull.
Similar to class-level constraints, you can create custom constraint violations on single parametersinstead of all parameters when validating a cross-parameter constraint. Just obtain a node builderfrom theConstraintValidatorContext passed toisValid() and add a parameter node by callingaddParameterNode(). In the example you could use this to create a constraint violation on the enddate parameter of the validated method.
In rare situations a constraint is both, generic and cross-parameter. This is the case if aconstraint has a validator class which is annotated with@SupportedValidationTarget({ValidationTarget.PARAMETERS, ValidationTarget.ANNOTATED_ELEMENT}) or ifit has a generic and a cross-parameter validator class.
When declaring such a constraint on a method which has parameters and also a return value, theintended constraint target can’t be determined. Constraints which are generic and cross-parameter atthe same time, must therefore define a membervalidationAppliesTo() which allows the constraint userto specify the constraint’s target as shown inExample 6.12, “Generic and cross-parameter constraint”.
Example 6.12. Generic and cross-parameter constraint
package org.hibernate.validator.referenceguide.chapter06.crossparameter;@Constraint(validatedBy = {ScriptAssertObjectValidator.class,ScriptAssertParametersValidator.class})@Target({ TYPE, FIELD, PARAMETER, METHOD, CONSTRUCTOR, ANNOTATION_TYPE })@Retention(RUNTIME)@Documentedpublic @interface ScriptAssert {String message() default "{org.hibernate.validator.referenceguide.chapter06." +"crossparameter.ScriptAssert.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };String script();ConstraintTarget validationAppliesTo() default ConstraintTarget.IMPLICIT;}The@ScriptAssert constraint has two validators (not shown), a generic and a cross-parameter one andthus defines the membervalidationAppliesTo(). The default valueIMPLICIT allows to derive thetarget automatically in situations where this is possible (e.g. if the constraint is declared on afield or on a method which has parameters but no return value).
If the target can not be determined implicitly, it must be set by the user to eitherPARAMETERS orRETURN_VALUE as shown inExample 6.13, “Specifying the target for a generic and cross-parameter constraint”.
Example 6.13. Specifying the target for a generic and cross-parameter constraint
@ScriptAssert(script = "arg1.size() <= arg0", validationAppliesTo = ConstraintTarget.PARAMETERS)public Car buildCar(int seatCount, List<Passenger> passengers) {//...}Looking at thelicensePlate field of theCar class inExample 6.6, “Applying the@CheckCase constraint”, you see threeconstraint annotations already. In complexer scenarios, where even more constraints could be appliedto one element, this might become a bit confusing easily. Furthermore, if there was alicensePlatefield in another class, you would have to copy all constraint declarations to the other class aswell, violating the DRY principle.
You can address this kind of problem by creating higher level constraints, composed from severalbasic constraints.Example 6.14, “Creating a composing constraint@ValidLicensePlate” shows a composed constraint annotation whichcomprises the constraints@NotNull,@Size and@CheckCase:
Example 6.14. Creating a composing constraint@ValidLicensePlate
package org.hibernate.validator.referenceguide.chapter06.constraintcomposition;@NotNull@Size(min = 2, max = 14)@CheckCase(CaseMode.UPPER)@Target({ METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = { })@Documentedpublic @interface ValidLicensePlate {String message() default "{org.hibernate.validator.referenceguide.chapter06." +"constraintcomposition.ValidLicensePlate.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };}To create a composed constraint, simply annotate the constraint declaration with its comprisingconstraints. If the composed constraint itself requires a validator, this validator is to bespecified within the@Constraint annotation. For composed constraints which don’t need an additionalvalidator such as@ValidLicensePlate, just setvalidatedBy() to an empty array.
Using the new composed constraint at thelicensePlate field is fully equivalent to the previousversion, where the three constraints were declared directly at the field itself:
Example 6.15. Application of composing constraintValidLicensePlate
package org.hibernate.validator.referenceguide.chapter06.constraintcomposition;public class Car {@ValidLicensePlateprivate String licensePlate;//...}The set ofConstraintViolations retrieved when validating aCar instance will contain an entry foreach violated composing constraint of the@ValidLicensePlate constraint. If you rather prefer asingleConstraintViolation in case any of the composing constraints is violated, the@ReportAsSingleViolation meta constraint can be used as follows:
Example 6.16. Using @ReportAsSingleViolation
//...@ReportAsSingleViolationpublic @interface ValidLicensePlate {String message() default "{org.hibernate.validator.referenceguide.chapter06." +"constraintcomposition.ValidLicensePlate.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };}So far we have used the default configuration source for Bean Validation, namely annotations.However, there also exist two kinds of XML descriptors allowing configuration via XML. The firstdescriptor describes general Bean Validation behaviour and is provided asMETA-INF/validation.xml.The second one describes constraint declarations and closely matches the constraint declarationapproach via annotations. Let’s have a look at these two document types.
The XSD files are available viahttp://www.jboss.org/xml/ns/javax/validation/configuration andhttp://www.jboss.org/xml/ns/javax/validation/mapping.
The key to enable XML configuration for Hibernate Validator is the fileMETA-INF/validation.xml.If this file exists on the classpath its configuration will be applied when theValidatorFactorygets created.Figure 7.1, “Validation configuration schema” shows a model view of the XML schema to whichvalidation.xml has to adhere.
Example 7.1, “validation.xml”shows the several configuration options ofvalidation.xml. All settings are optional and the sameconfiguration options are also available programmatically throughjavax.validation.Configuration. Infact the XML configuration will be overridden by values explicitly specified via the programmaticAPI. It is even possible to ignore the XML configuration completely viaConfiguration#ignoreXmlConfiguration(). See alsoSection 8.2, “Configuring aValidatorFactory”.
Example 7.1. validation.xml
<validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration"> <default-provider>com.acme.ValidationProvider</default-provider> <message-interpolator>com.acme.MessageInterpolator</message-interpolator> <traversable-resolver>com.acme.TraversableResolver</traversable-resolver> <constraint-validator-factory> com.acme.ConstraintValidatorFactory </constraint-validator-factory> <parameter-name-provider>com.acme.ParameterNameProvider</parameter-name-provider> <executable-validation enabled="true"> <default-validated-executable-types> <executable-type>CONSTRUCTORS</executable-type> <executable-type>NON_GETTER_METHODS</executable-type> <executable-type>GETTER_METHODS</executable-type> </default-validated-executable-types> </executable-validation> <constraint-mapping>META-INF/validation/constraints-car.xml</constraint-mapping> <property name="hibernate.validator.fail_fast">false</property></validation-config>There must only be one file namedMETA-INF/validation.xml on the classpath. If more than one isfound an exception is thrown.
The nodedefault-provider allows to choose the Bean Validation provider. This is useful if there ismore than one provider on the classpath.message-interpolator,traversable-resolver,constraint-validator-factory andparameter-name-provider allow to customize the usedimplementations for the interfacesMessageInterpolator,TraversableResolver,ConstraintValidatorFactory andParameterNameProvider defined in thejavax.validation package.See the sub-sections ofSection 8.2, “Configuring aValidatorFactory” for more information about theseinterfaces.
executable-validation and its subnodes define defaults for method validation. The Bean Validationspecification defines constructor and non getter methods as defaults. The enabled attribute acts asglobal switch to turn method validation on and off (see alsoChapter 3,Declaring and validating method constraints).
Via theconstraint-mapping element you can list an arbitrary number of additional XML filescontaining the actual constraint configuration. Mapping file names must be specified using theirfully-qualified name on the classpath. Details on writing mapping files can be found in the nextsection.
Last but not least, you can specify provider specific properties via theproperty nodes. In theexample we are using the Hibernate Validator specifichibernate.validator.fail_fast property (seeSection 11.2, “Fail fast mode”).
Expressing constraints in XML is possible via files adhering to the schema seen inFigure 7.2, “Validation mapping schema”. Note that these mapping files are only processed if listed viaconstraint-mapping invalidation.xml.
Example 7.2, “Bean constraints configured via XML” shows how the classes Car and RentalCar fromExample 5.3, “Car” resp.Example 5.7, “ClassRentalCar with redefined default group” could be mapped in XML.
Example 7.2. Bean constraints configured via XML
<constraint-mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.1.xsd" xmlns="http://jboss.org/xml/ns/javax/validation/mapping" version="1.1"> <default-package>org.hibernate.validator.referenceguide.chapter05</default-package> <bean ignore-annotations="true"> <field name="manufacturer"> <constraint annotation="javax.validation.constraints.NotNull"/> </field> <field name="licensePlate"> <constraint annotation="javax.validation.constraints.NotNull"/> </field> <field name="seatCount"> <constraint annotation="javax.validation.constraints.Min"> <element name="value">2</element> </constraint> </field> <field name="driver"> <valid/> </field> <getter name="passedVehicleInspection" ignore-annotations="true"> <constraint annotation="javax.validation.constraints.AssertTrue"> <message>The car has to pass the vehicle inspection first</message> <groups> <value>CarChecks</value> </groups> <element name="max">10</element> </constraint> </getter> </bean> <bean ignore-annotations="true"> <class ignore-annotations="true"> <group-sequence> <value>RentalCar</value> <value>CarChecks</value> </group-sequence> </class> </bean> <constraint-definition annotation="org.mycompany.CheckCase"> <validated-by include-existing-validators="false"> <value>org.mycompany.CheckCaseValidator</value> </validated-by> </constraint-definition></constraint-mappings>Example 7.3, “Method constraints configured via XML” shows how the constraints fromExample 3.1, “Declaring method and constructor parameter constraints”,Example 3.4, “Declaring method and constructor return value constraints”andExample 3.3, “Specifying a constraint’s target” can be expressed in XML.
Example 7.3. Method constraints configured via XML
<constraint-mappings xmlns="http://jboss.org/xml/ns/javax/validation/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.1.xsd" version="1.1"> <default-package>org.hibernate.validator.referenceguide.chapter07</default-package> <bean ignore-annotations="true"> <constructor> <return-value> <constraint annotation="ValidRentalStation"/> </return-value> </constructor> <constructor> <parameter type="java.lang.String"> <constraint annotation="javax.validation.constraints.NotNull"/> </parameter> </constructor> <method name="getCustomers"> <return-value> <constraint annotation="javax.validation.constraints.NotNull"/> <constraint annotation="javax.validation.constraints.Size"> <element name="min">1</element> </constraint> </return-value> </method> <method name="rentCar"> <parameter type="Customer"> <constraint annotation="javax.validation.constraints.NotNull"/> </parameter> <parameter type="java.util.Date"> <constraint annotation="javax.validation.constraints.NotNull"/> <constraint annotation="javax.validation.constraints.Future"/> </parameter> <parameter type="int"> <constraint annotation="javax.validation.constraints.Min"> <element name="value">1</element> </constraint> </parameter> </method> </bean> <bean ignore-annotations="true"> <method name="buildCar"> <parameter type="java.util.List"/> <cross-parameter> <constraint annotation="ELAssert"> <element name="expression">...</element> <element name="validationAppliesTo">PARAMETERS</element> </constraint> </cross-parameter> </method> <method name="paintCar"> <parameter type="int"/> <return-value> <constraint annotation="ELAssert"> <element name="expression">...</element> <element name="validationAppliesTo">RETURN_VALUE</element> </constraint> </return-value> </method> </bean></constraint-mappings>The XML configuration is closely mirroring the programmatic API. For this reason it should sufficeto just add some comments.default-package is used for all fields where a class name is expected. Ifthe specified class is not fully qualified the configured default package will be used. Everymapping file can then have several bean nodes, each describing the constraints on the entity withthe specified class name.
A given class can only be configured once across all configuration files. The same applies forconstraint definitions for a given constraint annotation. It can only occur in one mapping file. Ifthese rules are violated aValidationException is thrown.
Settingignore-annotations totrue means that constraint annotations placed on the configured beanare ignored. The default for this value is true.ignore-annotations is also available for the nodesclass,fields,getter,constructor,method,parameter,cross-parameter andreturn-value.If not explicitly specified on these levels the configured bean value applies.
The nodesclass,field,getter,constructor andmethod (and its sub node parameter) determine onwhich level the constraint gets placed. Theconstraint node is then used to add a constraint on thecorresponding level. Each constraint definition must define the class via theannotation attribute.The constraint attributes required by the Bean Validation specification (message,groups andpayload) have dedicated nodes. All other constraint specific attributes are configured using theelement node.
Theclass node also allows to reconfigure the default group sequence (seeSection 5.3, “Redefining the default group sequence”) via thegroup-sequence node. Not shown in the example is the useofconvert-group tospecify group conversions (seeSection 5.4, “Group conversion”). This node is available onfield,getter,parameter andreturn-value and specifies a from and to attribute to specify the groups.
Last but not least, the list ofConstraintValidator instances associated to a given constraintcan be altered via theconstraint-definition node. The annotation attribute represents the constraintannotation being altered. Thevalidated-by element represent the (ordered) list ofConstraintValidatorimplementations associated to the constraint. Ifinclude-existing-validator is set tofalse,validators defined on the constraint annotation are ignored. If set totrue, the list of constraintvalidators described in XML is concatenated to the list of validators specified on the annotation.
One use case for constraint-definition is to change the default constraint definition for@URL.Historically, Hibernate Validator’s default constraint validator for this constraint uses thejava.net.URL constructor to verify that an URL is valid.However, there is also a purely regular expression based version available which can be configured usingXML:
Using XML to register a regular expression based constraint definition for@URL.
<constraint-definition annotation="org.hibernate.validator.constraints.URL"> <validated-by include-existing-validators="false"> <value>org.hibernate.validator.constraintvalidators.RegexpURLValidator</value> </validated-by></constraint-definition>InSection 2.2.1, “Obtaining aValidator instance” you already saw one way for creating a Validator instance - viaValidation#buildDefaultValidatorFactory(). In this chapter you will learn how to use the othermethods injavax.validation.Validation in order to bootstrap specifically configured validators.
You obtain aValidator by retrieving aValidatorFactory via one of the static methods onjavax.validation.Validation and callinggetValidator() on the factory instance.
Example 8.1, “Bootstrapping defaultValidatorFactory andValidator” shows how to obtain a validator from the defaultvalidator factory:
Example 8.1. Bootstrapping defaultValidatorFactory andValidator
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();The generatedValidatorFactory andValidator instances are thread-safe and can be cached. AsHibernate Validator uses the factory as context for caching constraint metadata it is recommended towork with one factory instance within an application.
Bean Validation supports working with several providers such as Hibernate Validator within oneapplication. If more than one provider is present on the classpath, it is not guaranteed which oneis chosen when creating a factory viabuildDefaultValidatorFactory().
In this case you can explicitly specify the provider to use viaValidation#byProvider(), passing theprovider’sValidationProvider class as shown inExample 8.2, “BootstrappingValidatorFactory and Validator using a specific provider”.
Example 8.2. BootstrappingValidatorFactory and Validator using a specific provider
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class ).configure().buildValidatorFactory();Validator validator = validatorFactory.getValidator();Note that the configuration object returned byconfigure() allows to specifically customize thefactory before callingbuildValidatorFactory(). The available options are discussed later in thischapter.
Similarly you can retrieve the default validator factory for configuration which is demonstrated inExample 8.3, “Retrieving the defaultValidatorFactory for configuration”.
Example 8.3. Retrieving the defaultValidatorFactory for configuration
ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().buildValidatorFactory();Validator validator = validatorFactory.getValidator();If aValidatorFactory instance is no longer in use, it should be disposed by callingValidatorFactory#close(). This will free any resources possibly allocated by the factory.
By default, available Bean Validation providers are discovered using theJavaService Provider mechanism.
For that purpose, each provider includes the fileMETA-INF/services/javax.validation.spi.ValidationProvider, containing the fully qualified classname ofitsValidationProvider implementation. In the case of Hibernate Validator this isorg.hibernate.validator.HibernateValidator.
Depending on your environment and its classloading specifics, provider discovery via the Java’sservice loader mechanism might not work. In this case you can plug in a customValidationProviderResolver implementation which performs the provider retrieval. An example is OSGi,where you could implement a provider resolver which uses OSGi services for provider discovery.
To use a custom provider resolver pass it viaproviderResolver() as shown shown inExample 8.4, “Using a customValidationProviderResolver”.
Example 8.4. Using a customValidationProviderResolver
package org.hibernate.validator.referenceguide.chapter08;public class OsgiServiceDiscoverer implements ValidationProviderResolver {@Overridepublic List<ValidationProvider<?>> getValidationProviders() {//...}}ValidatorFactory validatorFactory = Validation.byDefaultProvider().providerResolver( new OsgiServiceDiscoverer() ).configure().buildValidatorFactory();Validator validator = validatorFactory.getValidator();By default validator factories retrieved fromValidation and any validators they create areconfigured as per the XML descriptorMETA-INF/validation.xml (seeChapter 7,Configuring via XML),if present.
If you want to disable the XML based configuration, you can do so by invokingConfiguration#ignoreXmlConfiguration().
The different values of the XML configuration can be accessed viaConfiguration#getBootstrapConfiguration(). This can for instance be helpful if you want to integrateBean Validation into a managed environment and want to create managed instances of the objectsconfigured via XML.
Using the fluent configuration API, you can override one or more of the settings when bootstrappingthe factory. The following sections show how to make use of the different options. Note that theConfiguration class exposes the default implementations of the different extension points which canbe useful if you want to use these as delegates for your custom implementations.
Message interpolators are used by the validation engine to create user readable error messages fromconstraint message descriptors.
In case the default message interpolation algorithm described inChapter 4,Interpolating constraint error messagesis not sufficient for your needs, you can pass in your own implementation of theMessageInterpolatorinterface viaConfiguration#messageInterpolator() as shown inExample 8.5, “Using a customMessageInterpolator”.
Example 8.5. Using a customMessageInterpolator
package org.hibernate.validator.referenceguide.chapter08;public class MyMessageInterpolator implements MessageInterpolator {@Overridepublic String interpolate(String messageTemplate, Context context) {//...}@Overridepublic String interpolate(String messageTemplate, Context context, Locale locale) {//...}}ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().messageInterpolator( new MyMessageInterpolator() ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();In some cases the validation engine should not access the state of a bean property. The most obviousexample for that is a lazily loaded property or association of a JPA entity. Validating this lazyproperty or association would mean that its state would have to be accessed, triggering a load fromthe database.
Which properties can be accessed and which ones not is controlled by querying theTraversableResolver interface.Example 8.6, “Using a customTraversableResolver” shows how to use acustom traversable resolver implementation.
Example 8.6. Using a customTraversableResolver
package org.hibernate.validator.referenceguide.chapter08;public class MyTraversableResolver implements TraversableResolver {@Overridepublic boolean isReachable(Object traversableObject,Node traversableProperty,Class<?> rootBeanType,Path pathToTraversableObject,ElementType elementType) {//...}@Overridepublic boolean isCascadable(Object traversableObject,Node traversableProperty,Class<?> rootBeanType,Path pathToTraversableObject,ElementType elementType) {//...}}ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().traversableResolver( new MyTraversableResolver() ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();If no specific traversable resolver has been configured, the default behavior is to consider all properties as reachable and cascadable.When using Hibernate Validator together with a JPA 2 provider such as Hibernate ORM, only those properties will be considered reachablewhich already have been loaded by the persistence provider and all properties will be considered cascadable.
ConstraintValidatorFactory is the extension point for customizing how constraint validators areinstantiated and released.
The defaultConstraintValidatorFactory provided by Hibernate Validator requires a public no-argconstructor to instantiateConstraintValidator instances (seeSection 6.1.2, “The constraint validator”).Using a customConstraintValidatorFactory offers for example the possibility to use dependencyinjection in constraint validator implementations.
To configure a custom constraint validator factory callConfiguration#constraintValidatorFactory()(seeExample 8.7, “Using a customConstraintValidatorFactory”.
Example 8.7. Using a customConstraintValidatorFactory
package org.hibernate.validator.referenceguide.chapter08;public class MyConstraintValidatorFactory implements ConstraintValidatorFactory {@Overridepublic <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {//...}@Overridepublic void releaseInstance(ConstraintValidator<?, ?> instance) {//...}}ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().constraintValidatorFactory( new MyConstraintValidatorFactory() ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();Any constraint implementations relying onConstraintValidatorFactory behaviors specific to animplementation (dependency injection, no no-arg constructor and so on) are not considered portable.
ConstraintValidatorFactory implementations should not cache validator instances as the state of eachinstance can be altered in theinitialize() method.
In case a method or constructor parameter constraint is violated, theParameterNameProviderinterface is used to retrieve the parameter name and make it available to the user via theproperty path of the constraint violation.
The default implementation returns parameter names in the form ofarg0,arg1 etc, while customimplementations can retrieve the parameter names using methods such as parameter annotations,debug symbols, or Java 8 reflection.
An implementation for retrieving the parameter names using reflection in Java 8 is provided withReflectionParameterNameProvider. For this parameter name provider to work, thesource must be compiled using the–parameters compiler argument. Otherwise, the provider willreturn synthetic names in the form ofarg0,arg1, etc.
To useReflectionParameterNameProvider or another custom provider either pass an instance ofthe provider during bootstrapping as shown inExample 8.8, “Using a customParameterNameProvider”,or specify the fully qualified class name of the provider as value forthe<parameter-name-provider> element in theMETA-INF/validation.xml file(seeSection 7.1, “Configuring the validator factory invalidation.xml”). This is demonstrated inExample 8.8, “Using a customParameterNameProvider”.
Example 8.8. Using a customParameterNameProvider
package org.hibernate.validator.referenceguide.chapter08;public class MyParameterNameProvider implements ParameterNameProvider {@Overridepublic List<String> getParameterNames(Constructor<?> constructor) {//...}@Overridepublic List<String> getParameterNames(Method method) {//...}}ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().parameterNameProvider( new MyParameterNameProvider() ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();Hibernate Validator comes with a customParameterNameProvider implementation based on theParaNamer library which provides several waysfor obtaining parameter names at runtime. Refer toSection 11.10, “ParaNamer basedParameterNameProvider”to learn more about this specific implementation.
As discussed earlier you can configure the constraints applying for your Java beans using XML basedconstraint mappings.
Besides the mapping files specified inMETA-INF/validation.xml you can add further mappings viaConfiguration#addMapping() (seeExample 8.9, “Adding constraint mapping streams”). Note that the passed inputstream(s) must adhere to the XML schema for constraint mappings presented inSection 7.2, “Mapping constraints viaconstraint-mappings”.
Example 8.9. Adding constraint mapping streams
InputStream constraintMapping1 = ...;InputStream constraintMapping2 = ...;ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().addMapping( constraintMapping1 ).addMapping( constraintMapping2 ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();You should close any passed input stream after the validator factory has been created.
Via the configuration object returned byValidation#byProvider() provider specific options can beconfigured.
In case of Hibernate Validator this e.g. allows you to enable the fail fast mode and pass one ormore programmatic constraint mappings as demonstrated inExample 8.10, “Setting Hibernate Validator specific options”.
Example 8.10. Setting Hibernate Validator specific options
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class ).configure().failFast( true ).addMapping( (ConstraintMapping) null ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();Alternatively, provider-specific options can be passed viaConfiguration#addProperty(). HibernateValidator supports enabling the fail fast mode that way, too:
Example 8.11. Enabling a Hibernate Validator specific option viaaddProperty()
ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class ).configure().addProperty( "hibernate.validator.fail_fast", "true" ).buildValidatorFactory();Validator validator = validatorFactory.getValidator();Refer toSection 11.2, “Fail fast mode” andSection 11.3, “Programmatic constraint declaration” to learn more about the fail fastmode and the constraint declaration API.
When working with a configured validator factory it can occasionally be required to apply adifferent configuration to a singleValidator instance.Example 8.12, “Configuring aValidator instance viausingContext()” shows how this canbe achieved by callingValidatorFactory#usingContext().
Example 8.12. Configuring aValidator instance viausingContext()
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();Validator validator = validatorFactory.usingContext().messageInterpolator( new MyMessageInterpolator() ).traversableResolver( new MyTraversableResolver() ).getValidator();The Bean Validation specification provides not only a validation engine, but also an API forretrieving constraint metadata in a uniform way, no matter whether the constraints are declaredusing annotations or via XML mappings. Read this chapter to learn more about this API and itspossibilities. You can find all the metadata API types in the packagejavax.validation.metadata.
The examples presented in this chapter are based on the classes and constraint declarations shown inExample 9.1, “Example classes”.
Example 9.1. Example classes
package org.hibernate.validator.referenceguide.chapter07;public class Person {public interface Basic {}@NotNullprivate String name;//getters and setters ...}public interface Vehicle {public interface Basic {}@NotNull(groups = Vehicle.Basic.class)String getManufacturer();}@ValidCarpublic class Car implements Vehicle {public interface SeverityInfo extends Payload {}private String manufacturer;@NotNull@Size(min = 2, max = 14)private String licensePlate;private Person driver;private String modelName;public Car() {}public Car(@NotNull String manufacturer,String licencePlate,Person driver,String modelName) {this.manufacturer = manufacturer;this.licensePlate = licencePlate;this.driver = driver;this.modelName = modelName;}public void driveAway(@Max(75) int speed) {//...}@LuggageCountMatchesPassengerCount(piecesOfLuggagePerPassenger = 2,validationAppliesTo = ConstraintTarget.PARAMETERS,payload = SeverityInfo.class,message = "There must not be more than {piecesOfLuggagePerPassenger} pieces of " +"luggage per passenger.")public void load(List<Person> passengers, List<PieceOfLuggage> luggage) {//...}@Override@Size(min = 3)public String getManufacturer() {return manufacturer;}public void setManufacturer(String manufacturer) {this.manufacturer = manufacturer;}@Valid@ConvertGroup(from = Default.class, to = Person.Basic.class)public Person getDriver() {return driver;}//further getters and setters...}The entry point into the metadata API is the methodValidator#getConstraintsForClass(), whichreturns an instance of theBeanDescriptor interface. Using thisdescriptor, you can obtain metadata for constraints declared directly on the bean itself (class- orproperty-level), but also retrieve metadata descriptors representing single properties, methods andconstructors.
Example 9.2, “UsingBeanDescriptor” demonstrates how to retrieve aBeanDescriptor for theCar class and how to use this descriptor in form of assertions.
If a constraint declaration hosted by the requested class is invalid, aValidationException is thrown.
Example 9.2. UsingBeanDescriptor
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();BeanDescriptor carDescriptor = validator.getConstraintsForClass( Car.class );assertTrue( carDescriptor.isBeanConstrained() );//one class-level constraintassertEquals( 1, carDescriptor.getConstraintDescriptors().size() );//manufacturer, licensePlate, driverassertEquals( 3, carDescriptor.getConstrainedProperties().size() );//property has constraintassertNotNull( carDescriptor.getConstraintsForProperty( "licensePlate" ) );//property is marked with @ValidassertNotNull( carDescriptor.getConstraintsForProperty( "driver" ) );//constraints from getter method in interface and implementation class are returnedassertEquals(2,carDescriptor.getConstraintsForProperty( "manufacturer" ).getConstraintDescriptors().size());//property is not constrainedassertNull( carDescriptor.getConstraintsForProperty( "modelName" ) );//driveAway(int), load(List<Person>, List<PieceOfLuggage>)assertEquals( 2, carDescriptor.getConstrainedMethods( MethodType.NON_GETTER ).size() );//driveAway(int), getManufacturer(), getDriver(), load(List<Person>, List<PieceOfLuggage>)assertEquals(4,carDescriptor.getConstrainedMethods( MethodType.NON_GETTER, MethodType.GETTER ).size());//driveAway(int)assertNotNull( carDescriptor.getConstraintsForMethod( "driveAway", int.class ) );//getManufacturer()assertNotNull( carDescriptor.getConstraintsForMethod( "getManufacturer" ) );//setManufacturer() is not constrainedassertNull( carDescriptor.getConstraintsForMethod( "setManufacturer", String.class ) );//Car(String, String, Person, String)assertEquals( 1, carDescriptor.getConstrainedConstructors().size() );//Car(String, String, Person, String)assertNotNull(carDescriptor.getConstraintsForConstructor(String.class,String.class,Person.class,String.class));You can determine whether the specified class hosts any class- or property-level constraints viaisBeanConstrained(). Method or constructor constraints are not considered byisBeanConstrained().
The methodgetConstraintDescriptors() is common to all descriptors derived fromElementDescriptor(seeSection 9.4, “ElementDescriptor”) and returns a set of descriptors representing theconstraints directly declared on the given element. In case ofBeanDescriptor, the bean’s class-level constraints are returned. More details onConstraintDescriptor can be found inSection 9.6, “ConstraintDescriptor”.
ViagetConstraintsForProperty(),getConstraintsForMethod() andgetConstraintsForConstructor() youcan obtain a descriptor representing one given property or executable element, identified by itsname and, in case of methods and constructors, parameter types. The different descriptor typesreturned by these methods are described in the following sections.
Note that these methods consider constraints declared at super-types according to the rules forconstraint inheritance as described inSection 2.1.5, “Constraint inheritance”. An example is thedescriptor for themanufacturer property, which provides access to all constraints defined onVehicle#getManufacturer() and the implementing methodCar#getManufacturer().null is returned incase the specified element does not exist or is not constrained.
The methodsgetConstrainedProperties(),getConstrainedMethods() andgetConstrainedConstructors()return (potentially empty) sets with all constrained properties, methods and constructors,respectively. An element is considered constrained, if it has at least one constraint or is markedfor cascaded validation. When invokinggetConstrainedMethods(), you can specify the type of themethods to be returned (getters, non-getters or both).
The interfacePropertyDescriptor represents one given property of aclass. It is transparent whether constraints are declared on a field or a property getter, providedthe JavaBeans naming conventions are respected.Example 9.3, “UsingPropertyDescriptor” showshow to use thePropertyDescriptor interface.
Example 9.3. UsingPropertyDescriptor
PropertyDescriptor licensePlateDescriptor = carDescriptor.getConstraintsForProperty("licensePlate");//"licensePlate" has two constraints, is not marked with @Valid and defines no group conversionsassertEquals( "licensePlate", licensePlateDescriptor.getPropertyName() );assertEquals( 2, licensePlateDescriptor.getConstraintDescriptors().size() );assertTrue( licensePlateDescriptor.hasConstraints() );assertFalse( licensePlateDescriptor.isCascaded() );assertTrue( licensePlateDescriptor.getGroupConversions().isEmpty() );PropertyDescriptor driverDescriptor = carDescriptor.getConstraintsForProperty( "driver" );//"driver" has no constraints, is marked with @Valid and defines one group conversionassertEquals( "driver", driverDescriptor.getPropertyName() );assertTrue( driverDescriptor.getConstraintDescriptors().isEmpty() );assertFalse( driverDescriptor.hasConstraints() );assertTrue( driverDescriptor.isCascaded() );assertEquals( 1, driverDescriptor.getGroupConversions().size() );UsinggetConstrainedDescriptors(), you can retrieve a set ofConstraintDescriptors providing moreinformation on the individual constraints of a given property. The methodisCascaded() returnstrue, if the property is marked for cascaded validation (either using the@Valid annotation or viaXML),false otherwise. Any configured group conversions are returned bygetGroupConversions(). SeeSection 9.5, “GroupConversionDescriptor” for more details onGroupConversionDescriptor.
Constrained methods and constructors are represented by the interfacesMethodDescriptorandConstructorDescriptor, respectively.Example 9.4, “UsingMethodDescriptor andConstructorDescriptor” demonstrates how to work with thesedescriptors.
Example 9.4. UsingMethodDescriptor andConstructorDescriptor
//driveAway(int) has a constrained parameter and an unconstrained return valueMethodDescriptor driveAwayDescriptor = carDescriptor.getConstraintsForMethod("driveAway",int.class);assertEquals( "driveAway", driveAwayDescriptor.getName() );assertTrue( driveAwayDescriptor.hasConstrainedParameters() );assertFalse( driveAwayDescriptor.hasConstrainedReturnValue() );//always returns an empty set; constraints are retrievable by navigating to//one of the sub-descriptors, e.g. for the return valueassertTrue( driveAwayDescriptor.getConstraintDescriptors().isEmpty() );ParameterDescriptor speedDescriptor = driveAwayDescriptor.getParameterDescriptors().get( 0 );//The "speed" parameter is located at index 0, has one constraint and is not cascaded//nor does it define group conversionsassertEquals( "arg0", speedDescriptor.getName() );assertEquals( 0, speedDescriptor.getIndex() );assertEquals( 1, speedDescriptor.getConstraintDescriptors().size() );assertFalse( speedDescriptor.isCascaded() );assert speedDescriptor.getGroupConversions().isEmpty();//getDriver() has no constrained parameters but its return value is marked for cascaded//validation and declares one group conversionMethodDescriptor getDriverDescriptor = carDescriptor.getConstraintsForMethod("getDriver");assertFalse( getDriverDescriptor.hasConstrainedParameters() );assertTrue( getDriverDescriptor.hasConstrainedReturnValue() );ReturnValueDescriptor returnValueDescriptor = getDriverDescriptor.getReturnValueDescriptor();assertTrue( returnValueDescriptor.getConstraintDescriptors().isEmpty() );assertTrue( returnValueDescriptor.isCascaded() );assertEquals( 1, returnValueDescriptor.getGroupConversions().size() );//load(List<Person>, List<PieceOfLuggage>) has one cross-parameter constraintMethodDescriptor loadDescriptor = carDescriptor.getConstraintsForMethod("load",List.class,List.class);assertTrue( loadDescriptor.hasConstrainedParameters() );assertFalse( loadDescriptor.hasConstrainedReturnValue() );assertEquals(1,loadDescriptor.getCrossParameterDescriptor().getConstraintDescriptors().size());//Car(String, String, Person, String) has one constrained parameterConstructorDescriptor constructorDescriptor = carDescriptor.getConstraintsForConstructor(String.class,String.class,Person.class,String.class);assertEquals( "Car", constructorDescriptor.getName() );assertFalse( constructorDescriptor.hasConstrainedReturnValue() );assertTrue( constructorDescriptor.hasConstrainedParameters() );assertEquals(1,constructorDescriptor.getParameterDescriptors().get( 0 ).getConstraintDescriptors().size());getName() returns the name of the given method or constructor. The methodshasConstrainedParameters() andhasConstrainedReturnValue() can be used to perform a quick checkwhether an executable element has any parameter constraints (either constraints on single parametersor cross-parameter constraints) or return value constraints.
Note that any constraints are not directly exposed onMethodDescriptor andConstructorDescriptor,but rather on dedicated descriptors representing an executable’s parameters, its return value andits cross-parameter constraints. To get hold of one of these descriptors, invokegetParameterDescriptors(),getReturnValueDescriptor() orgetCrossParameterDescriptor(),respectively.
These descriptors provide access to the element’s constraints (getConstraintDescriptors()) and, incase of parameters and return value, to its configuration for cascaded validation (isValid() andgetGroupConversions()). For parameters, you also can retrieve the index and the name, as returned bythe currently used parameter name provider (seeSection 8.2.4, “ParameterNameProvider”) viagetName()andgetIndex().
Getter methods following the JavaBeans naming conventions are considered as bean properties but alsoas constrained methods.
That means you can retrieve the related metadata either by obtaining aPropertyDescriptor (e.g.BeanDescriptor.getConstraintsForProperty("foo")) or by examining the return value descriptor of thegetter’sMethodDescriptor (e.g.BeanDescriptor.getConstraintsForMethod("getFoo").getReturnValueDescriptor()).
TheElementDiscriptorinterface is the common base class for theindividual descriptor types such asBeanDescriptor,PropertyDescriptor etc. BesidesgetConstraintDescriptors() it provides some more methods common to all descriptors.
hasConstraints() allows for a quick check whether an element has any direct constraints (e.g. class-level constraints in case ofBeanDescriptor).getElementClass() returns the Java type of the elementrepresented by a given descriptor. More specifically, the method returns
BeanDescriptor,PropertyDescriptor orParameterDescriptorrespectively,Object[].class when invoked onCrossParameterDescriptor,ConstructorDescriptor,MethodDescriptor orReturnValueDescriptor.void.class will be returned for methods which don’t have a return value.Example 9.5, “UsingElementDescriptor methods” shows how these methods are used.
Example 9.5. UsingElementDescriptor methods
PropertyDescriptor manufacturerDescriptor = carDescriptor.getConstraintsForProperty("manufacturer");assertTrue( manufacturerDescriptor.hasConstraints() );assertEquals( String.class, manufacturerDescriptor.getElementClass() );CrossParameterDescriptor loadCrossParameterDescriptor = carDescriptor.getConstraintsForMethod("load",List.class,List.class).getCrossParameterDescriptor();assertTrue( loadCrossParameterDescriptor.hasConstraints() );assertEquals( Object[].class, loadCrossParameterDescriptor.getElementClass() );Finally,ElementDescriptor offers access to theConstraintFinder API which allows you to query forconstraint metadata in a fine grained way.Example 9.6, “Usage ofConstraintFinder” shows how to retrieve aConstraintFinder instance viafindConstraints() and use the API to query for constraint metadata.
Example 9.6. Usage ofConstraintFinder
PropertyDescriptor manufacturerDescriptor = carDescriptor.getConstraintsForProperty("manufacturer");//"manufacturer" constraints are declared on the getter, not the fieldassertTrue(manufacturerDescriptor.findConstraints().declaredOn( ElementType.FIELD ).getConstraintDescriptors().isEmpty());//@NotNull on Vehicle#getManufacturer() is part of another groupassertEquals(1,manufacturerDescriptor.findConstraints().unorderedAndMatchingGroups( Default.class ).getConstraintDescriptors().size());//@Size on Car#getManufacturer()assertEquals(1,manufacturerDescriptor.findConstraints().lookingAt( Scope.LOCAL_ELEMENT ).getConstraintDescriptors().size());//@Size on Car#getManufacturer() and @NotNull on Vehicle#getManufacturer()assertEquals(2,manufacturerDescriptor.findConstraints().lookingAt( Scope.HIERARCHY ).getConstraintDescriptors().size());//Combining several filter optionsassertEquals(1,manufacturerDescriptor.findConstraints().declaredOn( ElementType.METHOD ).lookingAt( Scope.HIERARCHY ).unorderedAndMatchingGroups( Vehicle.Basic.class ).getConstraintDescriptors().size());ViadeclaredOn() you can search forConstraintDescriptors declared on certain element types. This isuseful to find property constraints declared on either fields or getter methods.
unorderedAndMatchingGroups() restricts the resulting constraints to those matching the givenvalidation group(s).
lookingAt() allows to distinguish between constraints directly specified on the element(Scope.LOCAL_ELEMENT) or constraints belonging to the element but hosted anywhere in the classhierarchy (Scope.HIERARCHY).
You can also combine the different options as shown in the last example.
Order is not respected byunorderedAndMatchingGroups(), but group inheritance and inheritance viasequence are.
All those descriptor types that represent elements which can be subject of cascaded validation(i.e.,PropertyDescriptor,ParameterDescriptor andReturnValueDescriptor) provide access to theelement’s group conversions viagetGroupConversions(). The returned set contains aGroupConversionDescriptorfor each configured conversion, allowing to retrievesource and target groups of the conversion.Example 9.7, “UsingGroupConversionDescriptor”shows an example.
Example 9.7. UsingGroupConversionDescriptor
PropertyDescriptor driverDescriptor = carDescriptor.getConstraintsForProperty( "driver" );Set<GroupConversionDescriptor> groupConversions = driverDescriptor.getGroupConversions();assertEquals( 1, groupConversions.size() );GroupConversionDescriptor groupConversionDescriptor = groupConversions.iterator().next();assertEquals( Default.class, groupConversionDescriptor.getFrom() );assertEquals( Person.Basic.class, groupConversionDescriptor.getTo() );Last but not least, theConstraintDescriptorinterface describes asingle constraint together with its composing constraints. Via an instance of this interface you getaccess to the constraint annotation and its parameters.
Example 9.8, “UsingConstraintDescriptor”shows how to retrieve default constraint attributes (such as message template, groups etc.) as wellas custom constraint attributes (piecesOfLuggagePerPassenger) and other metadata such as theconstraint’s annotation type and its validators from aConstraintDescriptor.
Example 9.8. UsingConstraintDescriptor
//descriptor for the @LuggageCountMatchesPassengerCount constraint on the//load(List<Person>, List<PieceOfLuggage>) methodConstraintDescriptor<?> constraintDescriptor = carDescriptor.getConstraintsForMethod("load",List.class,List.class).getCrossParameterDescriptor().getConstraintDescriptors().iterator().next();//constraint typeassertEquals(LuggageCountMatchesPassengerCount.class,constraintDescriptor.getAnnotation().annotationType());//standard constraint attributesassertEquals( SeverityInfo.class, constraintDescriptor.getPayload().iterator().next() );assertEquals(ConstraintTarget.PARAMETERS,constraintDescriptor.getValidationAppliesTo());assertEquals( Default.class, constraintDescriptor.getGroups().iterator().next() );assertEquals("There must not be more than {piecesOfLuggagePerPassenger} pieces of luggage per " +"passenger.",constraintDescriptor.getMessageTemplate());//custom constraint attributeassertEquals(2,constraintDescriptor.getAttributes().get( "piecesOfLuggagePerPassenger" ));//no composing constraintsassertTrue( constraintDescriptor.getComposingConstraints().isEmpty() );//validator classassertEquals(Arrays.<Class<?>>asList( LuggageCountMatchesPassengerCount.Validator.class ),constraintDescriptor.getConstraintValidatorClasses());Hibernate Validator is intended to be used to implement multi-layered data validation, whereconstraints are expressed in a single place (the annotated domain model) and checked in variousdifferent layers of the application. For this reason there are multiple integration points withother technologies.
Hibernate Validator integrates with both Hibernate and all pure Java Persistence providers.
When lazy loaded associations are supposed to be validated it is recommended to place the constrainton the getter of the association. Hibernate replaces lazy loaded associations with proxy instanceswhich get initialized/loaded when requested via the getter. If, in such a case, the constraint isplaced on field level the actual proxy instance is used which will lead to validation errors.
Out of the box, Hibernate (as of version 3.5.x) will translate the constraints you have defined foryour entities into mapping metadata. For example, if a property of your entity is annotated@NotNull, its columns will be declared asnot null in the DDL schema generated by Hibernate.
If, for some reason, the feature needs to be disabled, sethibernate.validator.apply_to_ddl tofalse. See alsoTable 2.2, “Bean Validation constraints” andTable 2.3, “Custom constraints”.
You can also limit the DDL constraint generation to a subset of the defined constraints by settingthe propertyorg.hibernate.validator.group.ddl. The property specifies the comma-separated, fullyspecified class names of the groups a constraint has to be part of in order to be considered for DDLschema generation.
Hibernate Validator has a built-in Hibernate event listener -org.hibernate.cfg.beanvalidation.BeanValidationEventListener -which is part of Hibernate ORM. Whenever aPreInsertEvent,PreUpdateEvent orPreDeleteEvent occurs, the listener will verify all constraints of the entityinstance and throw an exception if any constraint is violated. Per default objects will be checkedbefore any inserts or updates are made by Hibernate. Pre deletion events will per default nottrigger a validation. You can configure the groups to be validated per event type using thepropertiesjavax.persistence.validation.group.pre-persist,javax.persistence.validation.group.pre-update andjavax.persistence.validation.group.pre-remove.The values of these properties are the comma-separated, fully specified class names of the groupsto validate.Example 10.1, “Manual configuration ofBeanValidationEvenListener” shows the default values for theseproperties. In this case they could also be omitted.
On constraint violation, the event will raise a runtimeConstraintViolationException which containsa set ofConstraintViolation instances describing each failure.
If Hibernate Validator is present in the classpath, Hibernate ORM will use it transparently.To avoid validation even though Hibernate Validator is in the classpath setjavax.persistence.validation.mode to none.
If the beans are not annotated with validation annotations, there is no runtime performance cost.
In case you need to manually set the event listeners for Hibernate ORM, use the followingconfiguration inhibernate.cfg.xml:
Example 10.1. Manual configuration ofBeanValidationEvenListener
<hibernate-configuration> <session-factory> ... <property name="javax.persistence.validation.group.pre-persist"> javax.validation.groups.Default </property> <property name="javax.persistence.validation.group.pre-update"> javax.validation.groups.Default </property> <property name="javax.persistence.validation.group.pre-remove"></property> ... <event type="pre-update"> <listener/> </event> <event type="pre-insert"> <listener/> </event> <event type="pre-delete"> <listener/> </event> </session-factory></hibernate-configuration>If you are using JPA 2 and Hibernate Validator is in the classpath the JPA2 specification requiresthat Bean Validation gets enabled. The propertiesjavax.persistence.validation.group.pre-persist,javax.persistence.validation.group.pre-update andjavax.persistence.validation.group.pre-remove asdescribed inSection 10.1.2, “Hibernate event-based validation” can in this case be configured inpersistence.xml.persistence.xml also defines a node validation-mode which can be set toAUTO,CALLBACK,NONE. The default isAUTO.
In a JPA 1 you will have to create and register Hibernate Validator yourself. In case you are usingHibernate EntityManager you can add a customized version of theBeanValidationEventListenerdescribed inSection 10.1.2, “Hibernate event-based validation” to your project and register itmanually.
When working with JSF2 or JBoss Seam and Hibernate Validator (Bean Validation) is present in theruntime environment, validation is triggered for every field in the application.Example 10.2, “Usage of Bean Validation within JSF2”shows an example of thef:validateBean tag in a JSF page. ThevalidationGroups attribute is optionaland can be used to specify a comma separated list of validation groups. The default isjavax.validation.groups.Default. For more information refer to the Seam documentation or the JSF 2specification.
Example 10.2. Usage of Bean Validation within JSF2
<h:form> <f:validateBean validationGroups="javax.validation.groups.Default"> <h:inputText value=#{model.property}/> <h:selectOneRadio value=#{model.radioProperty}> ... </h:selectOneRadio> <!-- other input components here --> </f:validateBean></h:form>The integration between JSF 2 and Bean Validation is described in the "Bean Validation Integration"chapter ofJSR-314. It is interesting to know that JSF2 implements a customMessageInterpolator to ensure ensure proper localization. To encourage the useof the Bean Validation message facility, JSF 2 will per default only display the generated BeanValidation message. This can, however, be configured via the application resource bundle byproviding the following configuration ({0} is replaced with the Bean Validation message and{1} isreplaced with the JSF component label):
javax.faces.validator.BeanValidator.MESSAGE={1}: {0}The default is:
javax.faces.validator.BeanValidator.MESSAGE={0}As of version 1.1, Bean Validation is integrated with CDI (Contexts and Dependency Injection forJavaTM EE).
This integration provides CDI managed beans forValidator andValidatorFactory and enablesdependency injection in constraint validators as well as custom message interpolators, traversableresolvers, constraint validator factories and parameter name providers.
Furthermore, parameter and return value constraints on the methods and constructors of CDI managedbeans will automatically be validated upon invocation.
When your application runs on a Jave EE container, this integration is enabled by default. Whenworking with CDI in a Servlet container or in a pure Java SE environment, you can use the CDIportable extension provided by Hibernate Validator. To do so, add the portable extension to yourclass path as described inSection 1.1.2, “CDI”.
CDI’s dependency injection mechanism makes it very easy to retrieveValidatorFactory andValidatorinstances and use them in your managed beans. Just annotate instance fields of your bean with@javax.inject.Inject as shown inExample 10.3, “Retrieving validator factory and validator via@Inject”.
Example 10.3. Retrieving validator factory and validator via@Inject
package org.hibernate.validator.referenceguide.chapter10.cdi.validator;@ApplicationScopedpublic class RentalStation {@Injectprivate ValidatorFactory validatorFactory;@Injectprivate Validator validator;//...}The injected beans are the default validator factory and validator instances. In order to configurethem - e.g. to use a custom message interpolator - you can use the Bean Validation XML descriptorsas discussed inChapter 7,Configuring via XML.
If you are working with several Bean Validation providers you can make sure that factory andvalidator from Hibernate Validator are injected by annotating the injection points with the@HibernateValidator qualifier which is demonstrated inExample 10.4, “Using the@HibernateValidator qualifier annotation”.
Example 10.4. Using the@HibernateValidator qualifier annotation
package org.hibernate.validator.referenceguide.chapter10.cdi.validator.qualifier;@ApplicationScopedpublic class RentalStation {@Inject@HibernateValidatorprivate ValidatorFactory validatorFactory;@Inject@HibernateValidatorprivate Validator validator;//...}The fully-qualified name of the qualifier annotation isorg.hibernate.validator.cdi.HibernateValidator. Be sure to not importorg.hibernate.validator.HibernateValidator instead which is theValidationProvider implementationused for selecting Hibernate Validator when working with the bootstrapping API (seeSection 8.1, “RetrievingValidatorFactory andValidator”).
Via@Inject you also can inject dependencies into constraint validators and other Bean Validationobjects such asMessageInterpolator implementations etc.
Example 10.5, “Constraint validator with injected bean”demonstrates how an injected CDI bean is used in aConstraintValidator implementation to determinewhether the given constraint is valid or not. As the example shows, you also can work with the@PostConstruct and@PreDestroy callbacks to implement any required construction and destructionlogic.
Example 10.5. Constraint validator with injected bean
package org.hibernate.validator.referenceguide.chapter10.cdi.injection;public class ValidLicensePlateValidatorimplements ConstraintValidator<ValidLicensePlate, String> {@Injectprivate VehicleRegistry vehicleRegistry;@PostConstructpublic void postConstruct() {//do initialization logic...}@PreDestroypublic void preDestroy() {//do destruction logic...}@Overridepublic void initialize(ValidLicensePlate constraintAnnotation) {}@Overridepublic boolean isValid(String licensePlate, ConstraintValidatorContext constraintContext) {return vehicleRegistry.isValidLicensePlate( licensePlate );}}The method interception facilities of CDI allow for a very tight integration with Bean Validation’smethod validation functionality. Just put constraint annotations to the parameters and return valuesof the executables of your CDI beans and they will be validated automatically before (parameterconstraints) and after (return value constraints) a method or constructor is invoked.
Note that no explicit interceptor binding is required, instead the required method validationinterceptor will automatically be registered for all managed beans with constrained methods andconstructors.
The interceptororg.hibernate.validator.internal.cdi.interceptor.ValidationInterceptor isregistered byorg.hibernate.validator.internal.cdi.ValidationExtension. This happens implicitlywithin a Java EE 7 runtime environment or explicitly by adding thehibernate-validator-cdi artifact- seeSection 1.1.2, “CDI”
You can see an example inExample 10.6, “CDI managed beans with method-level constraints”.
Example 10.6. CDI managed beans with method-level constraints
package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation;@ApplicationScopedpublic class RentalStation {@Validpublic RentalStation() {//...}@NotNull@Validpublic Car rentCar(@NotNull Customer customer,@NotNull @Future Date startDate,@Min(1) int durationInDays) {//...}@NotNullList<Car> getAvailableCars() {//...}}package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation;@RequestScopedpublic class RentCarRequest {@Injectprivate RentalStation rentalStation;public void rentCar(String customerId, Date startDate, int duration) {//causes ConstraintViolationExceptionrentalStation.rentCar( null, null, -1 );}}Here theRentalStation bean hosts several method constraints. When invoking one of theRentalStationmethods from another bean such asRentCarRequest, the constraints of the invoked method areautomatically validated. If any illegal parameter values are passed as in the example, aConstraintViolationException will be thrown by the method interceptor, providing detailedinformation on the violated constraints. The same is the case if the method’s return value violatesany return value constraints.
Similarly, constructor constraints are validated automatically upon invocation. In the example theRentalStation object returned by the constructor will be validated since the constructor returnvalue is marked with@Valid.
Bean Validation allows for a fine-grained control of the executable types which are automaticallyvalidated. By default, constraints on constructors and non-getter methods are validated. Thereforethe@NotNull constraint on the methodRentalStation#getAvailableCars() inExample 10.6, “CDI managed beans with method-level constraints” gets not validated when the method is invoked.
You have the following options to configure which types of executables are validated uponinvocation:
@ValidateOnExecution annotation on the executable or type levelIf several sources of configuration are specified for a given executable,@ValidateOnExecutionn onthe executable level takes precedence over `@ValidateOnExecution on the type level and@ValidateOnExecution generally takes precedence over the globally configured types inMETA-INF/validation.xml.
Example 10.7, “Using@ValidateOnExecution” shows how to use the@ValidateOnExecution annotation:
Example 10.7. Using@ValidateOnExecution
package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.configuration;@ApplicationScoped@ValidateOnExecution(type = ExecutableType.ALL)public class RentalStation {@Validpublic RentalStation() {//...}@NotNull@Valid@ValidateOnExecution(type = ExecutableType.NONE)public Car rentCar(@NotNull Customer customer,@NotNull @Future Date startDate,@Min(1) int durationInDays) {//...}@NotNullpublic List<Car> getAvailableCars() {//...}}Here the methodrentCar() won’t be validated upon invocation because it is annotated with@ValidateOnExecution(type = ExecutableType.NONE). In contrast, the constructor and themethodgetAvailableCars() will be validated due to@ValidateOnExecution(type =ExecutableType.ALL) being given on the type level.ExecutableType.ALL is a more compact form forexplicitly specifying all the typesCONSTRUCTORS,GETTER_METHODS andNON_GETTER_METHODS.
Executable validation can be turned off globally by specifying<executable-validation enabled="false"/> inMETA-INF/validation.xml. In this case, any@ValidateOnExecution annotations are ignored.
Note that when a method overrides or implements a super-type method the configuration will be takenfrom that overridden or implemented method (as given via@ValidateOnExecution on the method itselfor on the super-type). This protects a client of the super-type method from an unexpected alterationof the configuration, e.g. disabling validation of an overridden executable in a sub-type.
In case a CDI managed bean overrides or implements a super-type method and this super-type methodhosts any constraints, it can happen that the validation interceptor is not properly registered withthe bean, resulting in the bean’s methods not being validated upon invocation. In this case you canspecify the executable typeIMPLICIT on the sub-class as shown inExample 10.8, “UsingExecutableType.IMPLICIT”, which makes sure that all required metadata is discoveredan the validation interceptor kicks in when the methods onExpressRentalStation are invoked.
Example 10.8. UsingExecutableType.IMPLICIT
package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.implicit;@ValidateOnExecution(type = ExecutableType.ALL)public interface RentalStation {@NotNull@ValidCar rentCar(@NotNull Customer customer,@NotNull @Future Date startDate,@Min(1) int durationInDays);}package org.hibernate.validator.referenceguide.chapter10.cdi.methodvalidation.implicit;@ApplicationScoped@ValidateOnExecution(type = ExecutableType.IMPLICIT)public class ExpressRentalStation implements RentalStation {@Overridepublic Car rentCar(Customer customer, Date startDate, @Min(1) int durationInDays) {//...}}When your application runs on a Java EE application server such ashttp://wildfly.org/,you also can obtainValidator andValidatorFactory instances via@Resource injection inmanaged objects such as EJBs etc., as shown inExample 10.9, “RetrievingValidator andValidatorFactory via@Resource injection”.
Example 10.9. RetrievingValidator andValidatorFactory via@Resource injection
package org.hibernate.validator.referenceguide.chapter10.javaee;@Statelesspublic class RentalStationBean {@Resourceprivate ValidatorFactory validatorFactory;@Resourceprivate Validator validator;//...}Alternatively you can obtain a validator and a validator factory from JNDI under the names"java:comp/Validator" and "java:comp/ValidatorFactory", respectively.
Similar to CDI-based injection via@Inject, these objects represent default validator and validatorfactory and thus can be configured using the XML descriptorMETA-INF/validation.xml (seeChapter 7,Configuring via XML).
When your application is CDI-enabled, the injected objects are CDI-aware as well and e.g. supportdependency injection in constraint validators.
Hibernate Validator also provides support for the unwrapping of JavaFX properties. If JavaFX is presenton the classpath aValidatedValueUnwrapper for JavaFX properties is automatically registered. In somecases, however, it is also necessary to explicitly use@UnwrapValidatedValue. This is required ifthe constraint validator resolution is not unique and there is a potential constraint validator forthe actual JavaFX property as well as the contained property value itself.SeeSection 11.11.2, “JavaFX unwrapper” for examples and further discussion.
ParameterMessageInterpolatorResourceBundleLocatorParameterNameProvider@Future and@PastIn this chapter you will learn how to make use of several features provided by Hibernate Validatorin addition to the functionality defined by the Bean Validation specification. This includes thefail fast mode, the API for programmatic constraint configuration and the boolean composition ofconstraints.
Using the features described in the following sections may result in application code which is notportable between Bean Validation providers.
Let’s start, however, with a look at the public API of Hibernate Validator.Table 11.1, “Hibernate Validator public API”lists all packages belonging to this API and describes their purpose. Note that when a package ispart of the public this is not necessarily true for its sub-packages.
Table 11.1. Hibernate Validator public API
| Packages | Description |
|---|---|
| Classes used by the Bean Validation bootstrap mechanism (eg. validation provider, configuration class); For more details seeChapter 8,Bootstrapping. |
| Hibernate Validator’s fluent API for constraint declaration; In |
| Some useful custom constraints provided by Hibernate Validator in addition to the built-in constraints defined by the Bean Validation specification; The constraints are described in detail inSection 2.3.2, “Additional constraints”. |
| Extended constraint validator context which allows to set custom attributes for message interpolation.Section 11.9.1, “ |
| The group sequence provider feature which allows you to define dynamic default group sequences in function of the validated object state; The specifics can be found inSection 5.3, “Redefining the default group sequence”. |
| Classes related to constraint message interpolation; The first package contains Hibernate Validator’s default message interpolator, |
| A |
| Extensions to the |
| An SPI for registering additional constraint validators programmatically, seeSection 11.12, “Providing constraint definitions”. |
| An SPI for customizing the retrieval of the current time when validating |
| Classes related to the processing of values prior to thei validation, seeSection 11.11, “Unwrapping values”. |
The public packages of Hibernate Validator fall into two categories: while the actual API parts areintended to beinvoked orused by clients (e.g. the API for programmatic constraint declarationor the custom constraints), the SPI (service provider interface) packages contain interfaces whichare intended to beimplemented by clients (e.g.ResourceBundleLocator).
Any packages not listed in that table are internal packages of Hibernate Validator and are notintended to be accessed by clients. The contents of these internal packages can change from releaseto release without notice, thus possibly breaking any client code relying on it.
Using the fail fast mode, Hibernate Validator allows to return from the current validation as soonas the first constraint violation occurs. This can be useful for the validation of large objectgraphs where you are only interested in a quick check whether there is any constraint violation atall.
Example 11.1, “Using the fail fast validation mode” shows how to bootstrap and use a fail fast enabled validator.
Example 11.1. Using the fail fast validation mode
package org.hibernate.validator.referenceguide.chapter11.failfast;public class Car {@NotNullprivate String manufacturer;@AssertTrueprivate boolean isRegistered;public Car(String manufacturer, boolean isRegistered) {this.manufacturer = manufacturer;this.isRegistered = isRegistered;}//getters and setters...}Validator validator = Validation.byProvider( HibernateValidator.class ) .configure() .failFast( true ) .buildValidatorFactory() .getValidator();Car car = new Car( null, false );Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );assertEquals( 1, constraintViolations.size() );Here the validated object actually fails to satisfy both the constraints declared on theCar class,yet the validation call yields only oneConstraintViolation since the fail fast mode is enabled.
There is no guarantee in which order the constraints are evaluated, i.e. it is not deterministicwhether the returned violation originates from the@NotNull or the@AssertTrue constraint. Ifrequired, a deterministic evaluation order can be enforced using group sequences as described inSection 5.2, “Defining group sequences”.
Refer toSection 8.2.6, “Provider-specific settings” to learn about the different ways of enabling thefail fast mode when bootstrapping a validator.
As per the Bean Validation specification, you can declare constraints using Java annotations and XMLbased constraint mappings.
In addition, Hibernate Validator provides a fluent API which allows for the programmaticconfiguration of constraints. Use cases include the dynamic addition of constraints at runtimedepending on some application state or tests where you need entities with different constraints indifferent scenarios but don’t want to implement actual Java classes for each test case.
By default, constraints added via the fluent API are additive to constraints configured via thestandard configuration capabilities. But it is also possible to ignore annotation and XML configuredconstraints where required.
The API is centered around theConstraintMapping interface. You obtain a new mapping viaHibernateValidatorConfiguration#createConstraintMapping() which you then can configure in a fluentmanner as shown inExample 11.2, “Programmatic constraint declaration”.
Example 11.2. Programmatic constraint declaration
HibernateValidatorConfiguration configuration = Validation .byProvider( HibernateValidator.class ) .configure();ConstraintMapping constraintMapping = configuration.createConstraintMapping();constraintMapping .type( Car.class ) .property( "manufacturer", FIELD ) .constraint( new NotNullDef() ) .property( "licensePlate", FIELD ) .ignoreAnnotations() .constraint( new NotNullDef() ) .constraint( new SizeDef().min( 2 ).max( 14 ) ) .type( RentalCar.class ) .property( "rentalStation", METHOD ) .constraint( new NotNullDef() );Validator validator = configuration.addMapping( constraintMapping ) .buildValidatorFactory() .getValidator();Constraints can be configured on multiple classes and properties using method chaining. Theconstraint definition classesNotNullDef and SizeDef are helper classes which allow to configureconstraint parameters in a type-safe fashion. Definition classes exist for all built-in constraintsin theorg.hibernate.validator.cfg.defs package. By callingignoreAnnotations() any constraintsconfigured via annotations or XML are ignored for the given element.
Each element (type, property, method etc.) may only be configured once within all the constraintmappings used to set up one validator factory. Otherwise aValidationException is raised.
It is not supported to add constraints to non-overridden supertype properties and methods byconfiguring a subtype. Instead you need to configure the supertype in this case.
Having configured the mapping, you must add it back to the configuration object from which you thencan obtain a validator factory.
For custom constraints you can either create your own definition classes extendingConstraintDef oryou can useGenericConstraintDef as seen inExample 11.3, “Programmatic declaration of a custom constraint”.
Example 11.3. Programmatic declaration of a custom constraint
ConstraintMapping constraintMapping = configuration.createConstraintMapping();constraintMapping .type( Car.class ) .property( "licensePlate", FIELD ) .constraint( new GenericConstraintDef<CheckCase>( CheckCase.class ) .param( "value", CaseMode.UPPER ) );By invokingvalid() you can mark a member for cascaded validation which is equivalent to annotatingit with@Valid. Configure any group conversions to be applied during cascaded validation using theconvertGroup() method (equivalent to@ConvertGroup). An example can be seen inExample 11.4, “Marking a property for cascaded validation”.
Example 11.4. Marking a property for cascaded validation
ConstraintMapping constraintMapping = configuration.createConstraintMapping();constraintMapping .type( Car.class ) .property( "driver", FIELD ) .constraint( new NotNullDef() ) .valid() .convertGroup( Default.class ).to( PersonDefault.class ) .type( Person.class ) .property( "name", FIELD ) .constraint( new NotNullDef().groups( PersonDefault.class ) );You can not only configure bean constraints using the fluent API but also method and constructorconstraints. As shown inExample 11.5, “Programmatic declaration of method and constructor constraints” constructors are identified by theirparameter types and methods by their name and parameter types. Having selected a method orconstructor, you can mark its parameters and/or return value for cascaded validation and addconstraints as well as cross-parameter constraints.
Example 11.5. Programmatic declaration of method and constructor constraints
ConstraintMapping constraintMapping = configuration.createConstraintMapping();constraintMapping .type( Car.class ) .constructor( String.class ) .parameter( 0 ) .constraint( new SizeDef().min( 3 ).max( 50 ) ) .returnValue() .valid() .method( "drive", int.class ) .parameter( 0 ) .constraint( new MaxDef().value ( 75 ) ) .method( "load", List.class, List.class ) .crossParameter() .constraint( new GenericConstraintDef<LuggageCountMatchesPassengerCount>( LuggageCountMatchesPassengerCount.class ).param( "piecesOfLuggagePerPassenger", 2 ) ) .method( "getDriver" ) .returnValue() .constraint( new NotNullDef() ) .valid();Last but not least you can configure the default group sequence or the default group sequenceprovider of a type as shown in the following example.
Example 11.6. Configuration of default group sequence and default group sequence provider
ConstraintMapping constraintMapping = configuration.createConstraintMapping();constraintMapping .type( Car.class ) .defaultGroupSequence( Car.class, CarChecks.class ) .type( RentalCar.class ) .defaultGroupSequenceProviderClass( RentalCarGroupSequenceProvider.class );If you are not bootstrapping a validator factory manuallybut work with the default factory as configured viaMETA-INF/validation.xml(seeChapter 7,Configuring via XML),you can add one or more constraint mappings by creating a constraint mapping contributor.To do so, implement theConstraintMappingContributor contract:
Example 11.7. CustomConstraintMappingContributor implementation
package org.hibernate.validator.referenceguide.chapter11.constraintapi;public class MyConstraintMappingContributor implements ConstraintMappingContributor {@Overridepublic void createConstraintMappings(ConstraintMappingBuilder builder) {builder.addConstraintMapping().type( Marathon.class ).property( "name", METHOD ).constraint( new NotNullDef() ).property( "numberOfHelpers", FIELD ).constraint( new MinDef().value( 1 ) );builder.addConstraintMapping().type( Runner.class ).property( "paidEntryFee", FIELD ).constraint( new AssertTrueDef() );}}You then need to specify the fully-qualified class name of the contributor implementation inMETA-INF/validation.xml,using the property keyhibernate.validator.constraint_mapping_contributor.
In case you specify a purely composed constraint - i.e. a constraint which has no validator itself but is solely madeup from other, composing constraints - on a method declaration, the validation engine cannot determine whether thatconstraint is to be applied as a return value constraint or as a cross-parameter constraint.
Hibernate Validator allows to resolve such ambiguities by specifying the@SupportedValidationTarget annotation on thedeclaration of the composed constraint type as shown inExample 11.8, “Specifying the validation target of a purely composed constraint”.The@ValidInvoiceAmount does not declare any validator, but it is solely composed by the@Min and@NotNullconstraints. The@SupportedValidationTarget ensures that the constraint is applied to the method return value whengiven on a method declaration.
Example 11.8. Specifying the validation target of a purely composed constraint
package org.hibernate.validator.referenceguide.chapter11.purelycomposed;@Min(value = 0)@NotNull@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)@Documented@Constraint(validatedBy = {})@SupportedValidationTarget(ValidationTarget.ANNOTATED_ELEMENT)@ReportAsSingleViolationpublic @interface ValidInvoiceAmount {String message() default "{org.hibernate.validator.referenceguide.chapter11.purelycomposed."+ "ValidInvoiceAmount.message}";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};@OverridesAttribute(constraint = Min.class, name = "value")long value();}Bean Validation specifies that the constraints of a composed constraint (seeSection 6.4, “Constraint composition”) are all combined via a logicalAND. This means all of thecomposing constraints need to return true in order for an overall successful validation.
Hibernate Validator offers an extension to this and allows you to compose constraints via a logicalOR orNOT. To do so you have to use the ConstraintComposition annotation and the enumCompositionType with its valuesAND,OR andALL_FALSE.
Example 11.9, “OR composition of constraints” shows how to build a composed constraint@PatternOrSizewhere only one of the composing constraints needs to be valid in order to pass the validation.Either the validated string is all lower-cased or it is between two and three characters long.
Example 11.9. OR composition of constraints
package org.hibernate.validator.referenceguide.chapter11.booleancomposition;@ConstraintComposition(OR)@Pattern(regexp = "[a-z]")@Size(min = 2, max = 3)@ReportAsSingleViolation@Target({ METHOD, FIELD })@Retention(RUNTIME)@Constraint(validatedBy = { })public @interface PatternOrSize {String message() default "{org.hibernate.validator.referenceguide.chapter11." +"booleancomposition.PatternOrSize.message}";Class<?>[] groups() default { };Class<? extends Payload>[] payload() default { };}UsingALL_FALSE as composition type implicitly enforces that only a single violation will getreported in case validation of the constraint composition fails.
Hibernate Validator provides an extension to thejavax.validation.Path API.For nodes ofElementKind.PROPERTY it allows to obtain the value of the represented property.To do so, narrow down a given node to the typeorg.hibernate.validator.path.PropertyNode usingNode#as(), as shown in the following example:
Example 11.10. Getting the value from property nodes
Building building = new Building();// Assume the name of the person violates a @Size constraintPerson bob = new Person( "Bob" );Apartment bobsApartment = new Apartment( bob );building.getApartments().add( bobsApartment );Set<ConstraintViolation<Building>> constraintViolations = validator.validate( building );Path path = constraintViolations.iterator().next().getPropertyPath();Iterator<Path.Node> nodeIterator = path.iterator();Path.Node node = nodeIterator.next();assertEquals( node.getName(), "apartments" );assertSame( node.as( PropertyNode.class ).getValue(), bobsApartment );node = nodeIterator.next();assertEquals( node.getName(), "resident" );assertSame( node.as( PropertyNode.class ).getValue(), bob );node = nodeIterator.next();assertEquals( node.getName(), "name" );assertEquals( node.as( PropertyNode.class ).getValue(), "Bob" );This is specifically useful to obtain the element ofSet properties on the property path (e.g.apartments in the example) which otherwise could not be identified (unlike forMap andList, there is no key nor index in this case).
Hibernate Validator requires per default an implementation of the Unified EL (seeSection 1.1.1, “Unified EL”) to be available. This is needed to allow the interpolationof constraint error messages using EL expressions as defined by Bean Validation 1.1.
For environments where you cannot or do not want to provide an EL implementation, Hibernate Validatorsoffers a non EL based message interpolator -org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator.
Refer toSection 4.2, “Custom message interpolation” to see how to plug in custom message interpolatorimplementations.
Constraint messages containing EL expressions will be returned un-interpolated byorg.hibernate.validator.messageinterpolation.ParameterMessageInterpolator. This also affectsbuilt-in default constraint messages which use EL expressions. At the momentDecimalMin andDecimalMax are affected.
WithResourceBundleLocator, Hibernate Validator provides an additional SPI which allows to retrieveerror messages from other resource bundles thanValidationMessages while still using the actualinterpolation algorithm as defined by the specification. Refer toSection 4.2.1, “ResourceBundleLocator” to learn how to make use of that SPI.
The Bean Validation specification offers at several points in its API the possibility to unwrap agiven interface to a implementor specific subtype. In the case of constraint violation creation inConstraintValidator implementations as well as message interpolation inMessageInterpolatorinstances, there existunwrap() methods for the provided context instances -ConstraintValidatorContext respectivelyMessageInterpolatorContext. Hibernate Validator providescustom extensions for both of these interfaces.
HibernateConstraintValidatorContext is a subtype ofConstraintValidatorContext which allows you to:
TimeProvider for getting the current time when validating theFuture and@Past constraints(seeSection 11.14, “Time providers for@Future and@Past”)This is useful if you for instance would like to customize the message of the@Future constraint.By default the message just is "must be in the future".Example 11.11, “Custom@Future validator with message parameters” showshow to include the current date in order to make the message more explicit.
Example 11.11. Custom@Future validator with message parameters
public class MyFutureValidator implements ConstraintValidator<Future, Date> {@Overridepublic void initialize(Future constraintAnnotation) {}@Overridepublic boolean isValid(Date value, ConstraintValidatorContext context) {if ( value == null ) {return true;}HibernateConstraintValidatorContext hibernateContext = context.unwrap(HibernateConstraintValidatorContext.class);Date now = new Date( hibernateContext.getTimeProvider().getCurrentTime() );if ( !value.after( now ) ) {hibernateContext.disableDefaultConstraintViolation();hibernateContext.addExpressionVariable( "now", now ).buildConstraintViolationWithTemplate( "Must be after ${now}" ).addConstraintViolation();return false;}return true;}}Note that the parameters specified viaaddExpressionVariable(String, Object) are global and applyfor all constraint violations created by thisisValid() invocation. This includes the defaultconstraint violation, but also all violations created by theConstraintViolationBuilder. You can,however, update the parameters between invocations ofConstraintViolationBuilder#addConstraintViolation().
This functionality is currently experimental and might change in future versions.
Hibernate Validator also offers a custom extension ofMessageInterpolatorContext, namelyHibernateMessageInterpolatorContext (seeExample 11.12, “HibernateMessageInterpolatorContext”). Thissubtype was introduced to allow a better integration of Hibernate Validator into the Glassfish. Theroot bean type was in this case needed to determine the right classloader for the message resourcebundle. If you have any other usecases, let us know.
Example 11.12. HibernateMessageInterpolatorContext
public interface HibernateMessageInterpolatorContext extends MessageInterpolator.Context {/** * Returns the currently validated root bean type. * * @return The currently validated root bean type. */Class<?> getRootBeanType();}Hibernate Validator comes with aParameterNameProvider implementation which leverages theParaNamer library.
This library provides several ways for obtaining parameter names at runtime, e.g. based on debugsymbols created by the Java compiler, constants with the parameter names woven into the bytecode ina post-compile step or annotations such as the@Named annotation from JSR 330.
In order to useParanamerParameterNameProvider, either pass an instance when bootstrapping avalidator as shown inExample 8.8, “Using a customParameterNameProvider” or specifyorg.hibernate.validator.parameternameprovider.ParanamerParameterNameProvider as value for the<parameter-name-provider> element in theMETA-INF/validation.xml file.
When using this parameter name provider, you need to add the ParaNamer library to your classpath. Itis available in the Maven Central repository with the group idcom.thoughtworks.paranamer and theartifact idparanamer.
By defaultParanamerParameterNameProvider retrieves parameter names from constants added to the bytecode at build time (viaDefaultParanamer) and debug symbols (viaBytecodeReadingParanamer).Alternatively you can specify aParanamer implementation of your choice when creating aParanamerParameterNameProvider instance.
Sometimes it is required to unwrap values prior to validating them. For example, inExample 11.13, “Applying a constraint to wrapped value of a JavaFX property” aJavaFX property typeis used to define an element of a domain model. The@Size constraint is meant to be applied to thestring value not the wrappingProperty instance.
Example 11.13. Applying a constraint to wrapped value of a JavaFX property
@Size(min = 3)private Property<String> name = new SimpleStringProperty( "Bob" );The concept of value unwrapping is considered experimental at this time and may evolve into moregeneral means of value handling in future releases. Please let us know about your use cases for suchfunctionality.
Bean properties in JavaFX are typically not of simple data types likeString orint, but arewrapped inProperty types which allows to make them observable, use them for data binding etc. Whenapplying a constraint such as@Size to an element of typeProperty<String> without furtherpreparation, an exception would be raised, indicating that no suitable validator for that constraintand data type can be found. Thus the validated value must be unwrapped from the containing propertyobject before looking up a validator and invoking it.
For unwrapping to occur aValidatedValueUnwrapper needs to be registered for the typerequiring unwrapping. ExampleExample 11.14, “Implementing the ValidatedValueUnwrapper interface” shows how thisschematically looks for a JavaFXPropertyValueUnwrapper. You just need to extend the SPI classValidatedValueUnwrapper and implement its abstract methods.
Example 11.14. Implementing the ValidatedValueUnwrapper interface
public class PropertyValueUnwrapper extends ValidatedValueUnwrapper<Property<?>> {@Overridepublic Object handleValidatedValue(Property<?> value) {//...}@Overridepublic Type getValidatedValueType(Type valueType) {//...}}TheValidatedValueUnwrapper needs also to be registered with theValidatorFactory:
Example 11.15. Registering a ValidatedValueUnwrapper
Validator validator = Validation.byProvider( HibernateValidator.class ).configure().addValidatedValueHandler( new PropertyValueUnwrapper() ).buildValidatorFactory().getValidator();Several unwrapper implementations can be registered. During constraint validator resolutionHibernate Validator automatically checks whether aValidatedValueUnwrapper exists for the validatedvalue. If so, unwrapping occurs automatically. In some cases, however, constraint validator instancesfor a given constraint might exist for the wrapper as well as the wrapped value (@NotNull for exampleapplies to all objects). In this case Hibernate Validator needs to be explicitly told which valueto validate. This can be done via@UnwrapValidatedValue(true) respectively@UnwrapValidatedValue(false).
Note that it is not specified which of the unwrapper implementations ischosen when more than one implementation is suitable to unwrap a given element.
Instead of programmatically registeringValidatedValueUnwrapper types, the fully-qualified namesof one ore more unwrapper implementations can be specifiedvia the configuration propertyhibernate.validator.validated_value_handlers which can be useful whenconfiguring the default validator factory using the descriptorMETA-INF/validation.xml (seeChapter 7,Configuring via XML).
Hibernate Validator provides built-in unwrapping forOptional introduced in Java 8.The unwrapper is registered automatically in Java 8 environments, and no further configuration isrequired. An example of unwrapping anOptional instance is shown inExample 11.16, “UnwrappingOptional instances”.
Example 11.16. UnwrappingOptional instances
@Size(min = 3)private Optional<String> firstName = Optional.of( "John" );@NotNull@UnwrapValidatedValue // UnwrapValidatedValue required since otherwise unclear which value to validateprivate Optional<String> lastName = Optional.of( "Doe" );Optional.empty() is treated asnull during validation. This means that for constraints wherenull is considered valid,Optional.empty() is similarly valid.
Hibernate Validator also provides built-in unwrapping for JavaFX property values. The unwrapper isregistered automatically for environments where JavaFX is present, and no further configuration isrequired.ObservableValue and its sub-types are supported.An example of some of the different ways in whichJavaFX property values can be unwrapped isshown inExample 11.17, “UnwrappingJavaFX properties”.
Example 11.17. UnwrappingJavaFX properties
@Min(value = 3)IntegerProperty integerProperty1 = new SimpleIntegerProperty( 4 );@Min(value = 3)Property<Number> integerProperty2 = new SimpleIntegerProperty( 4 );@Min(value = 3)ObservableValue<Number> integerProperty3 = new SimpleIntegerProperty( 4 );Unwrapping can also be used with object graphs (cascaded validation) as shown inExample 11.18, “UnwrappingOptional prior to cascaded validation via@Valid”.When validating the object holding theOptional<Person>, a cascaded validation of thePersonobject would be performed.
Example 11.18. UnwrappingOptional prior to cascaded validation via@Valid
@Validprivate Optional<Person> person = Optional.of( new Person() );public class Person {@Size(min =3)private String name = "Bob";}Bean Validation allows to (re-)define constraint definitions via XML in its constraint mappingfiles. SeeSection 7.2, “Mapping constraints viaconstraint-mappings” for more information andExample 7.2, “Bean constraints configured via XML”for an example. While this approach is sufficient for many use cases, it has it shortcomingsin others. Imagine for example a constraint library wanting to contribute constraintdefinitions for custom types. This library could provide a mapping file with their library, but thisfile still would need to be referenced by the user of the library. Luckily there are better ways.
The following concepts are considered experimental at this time. Let us know whether you find themuseful and whether they meet your needs.
Hibernate Validator allows to utilize Java’sServiceLoadermechanism to register additional constraint definitions. All you have to do is to add the filejavax.validation.ConstraintValidator toMETA-INF/services. In this service file you list thefully qualified classnames of your constraint validator classes (one per line). Hibernate Validatorwill automatically infer the constraint types they apply to.SeeConstraint definition via service filefor an example.
Example 11.19. META-INF/services/javax.validation.ConstraintValidator
# Assuming a custom constraint annotation @org.mycompany.CheckCaseorg.mycompany.CheckCaseValidator
To contribute default messages for your custom constraints, place a fileContributorValidationMessages.propertiesand/or its locale-specific specializations at the root your JAR. Hibernate Validator will consider theentries from all the bundles with this name found on the classpath in addition to those given inValidationMessages.properties.
This mechanism is also helpful when creating large multi-module applications: Instead of putting all the constraintmessages into one single bundle, you can have one resource bundle per module containing only those messages of that module.
While the service loader approach works in many scenarios, but not in all (think for exampleOSGi where service files are not visible), there is yet another way of contributing constraintdefinitions. You can provide one or more implementations ofConstraintDefinitionContributor toHibernateConfiguration during bootstrapping of theValidatorFactory - seeExample 11.20, “UsingConstraintDefinitionContributor to register constraint definitions”.
Example 11.20. UsingConstraintDefinitionContributor to register constraint definitions
public class CarTest {private static Validator validator;public static class MyConstraintDefinitionContributorimplements ConstraintDefinitionContributor {@Overridepublic void collectConstraintDefinitions(ConstraintDefinitionBuilder builder) {builder.constraint( ValidPassengerCount.class ).validatedBy( ValidPassengerCountValidator.class );}}@BeforeClasspublic static void setUpValidator() {HibernateValidatorConfiguration configuration = Validation.byProvider( HibernateValidator.class ).configure();ConstraintDefinitionContributor contributor = new MyConstraintDefinitionContributor();configuration.addConstraintDefinitionContributor( contributor );validator = configuration.buildValidatorFactory().getValidator();} // ...}Instead of programmatically registeringConstraintDefinitionContributor instances, thefully-qualified classnames of one or more implementations can be specified via thepropertyhibernate.validator.constraint_definition_contributors. This can be useful whenconfiguring the default validator factory usingMETA-INF/validation.xml (seeChapter 7,Configuring via XML).
One use case forConstraintDefinitionContributor is the ability to specify an alternativeconstraint validator for the@URL constraint. Historically, Hibernate Validator’s default constraintvalidator for this constraint uses thejava.net.URL constructor to validate an URL.However, there is also a purely regular expression based version available which can be configured usingaConstraintDefinitionContributor:
Using aConstraintDefinitionContributor to register a regular expression based constraint definition for@URL.
HibernateValidatorConfiguration configuration = Validation.byProvider( HibernateValidator.class ).configure();configuration.addConstraintDefinitionContributor(new ConstraintDefinitionContributor() {@Overridepublic void collectConstraintDefinitions(ConstraintDefinitionBuilder builder) {builder.constraint( URL.class ).includeExistingValidators( false ).validatedBy( RegexpURLValidator.class );}});There are several cases in which Hibernate Validator needs to load resources or classes given by name:
By default Hibernate Validator tries to load these resources via the current thread context classloader.If that’s not successful, Hibernate Validator’s own classloader will be tried as a fallback.
For cases where this strategy is not appropriate (e.g. modularized environments such as OSGi),you may provide a specific classloader for loading these resources when bootstrapping the validator factory:
Example 11.21. Providing a classloader for loading external resources and classes
ClassLoader classLoader = ...;Validator validator = Validation.byProvider( HibernateValidator.class ).configure().externalClassLoader( classLoader ).buildValidatorFactory().getValidator();In the case of OSGi, you could e.g. pass the loader of a class from the bundle bootstrapping Hibernate Validatoror a custom classloader implementation which delegates toBundle#loadClass() etc.
CallValidatorFactory#close() if a given validator factory instance is not needed any longer.Failure to do so may result in a classloader leak in cases where applications/bundles are re-deployed and a non-closedvalidator factory still is referenced by application code.
By default the current system time is used when validating the@Future and@Past constraints.In some cases it can be necessary though to work with another "logical" date rather than the system time,e.g. for testing purposes or in the context of batch applications which may require to run withyesterday’s date when re-running a failed job execution.
To address such scenarios, Hibernate Validator provides a custom contract for obtaining the current time,TimeProvider.Example 11.22, “Using a customTimeProvider” shows an implementation of this contract and its registration when bootstrapping a validator factory.
Example 11.22. Using a customTimeProvider
public class CustomTimeProvider implements TimeProvider {@Overridepublic long getCurrentTime() {Calendar now = ...;return now.getTimeInMillis();}}ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class ).configure().timeProvider( timeProvider ).buildValidatorFactory();Alternatively, you can specify the fully-qualified classname of aTimeProvider implementation using the propertyhibernate.validator.time_provider when configuring the default validator factory viaMETA-INF/validation.xml(seeChapter 7,Configuring via XML).
Have you ever caught yourself by unintentionally doing things like
@Past)Then the Hibernate Validator Annotation Processor is the right thing for you. It helps preventingsuch mistakes by plugging into the build process and raising compilation errors whenever constraintannotations are incorrectly used.
You can find the Hibernate Validator Annotation Processor as part of the distribution bundle onSourceforge or in theusual Maven repositories such as Maven Central under the GAVorg.hibernate:hibernate-validator-annotation-processor:5.2.5.Final.
The Hibernate Validator Annotation Processor is based on the "Pluggable Annotation Processing API"as defined byJSR 269 which is part of the JavaPlatform since Java 6.
As of Hibernate Validator 5.2.5.Final the Hibernate Validator Annotation Processor checks that:
@ValidThe behavior of the Hibernate Validator Annotation Processor can be controlled using theprocessor optionslisted in tableTable 12.1, “Hibernate Validator Annotation Processor options”:
Table 12.1. Hibernate Validator Annotation Processor options
| Option | Explanation |
|---|---|
| Controls how constraint problems are reported. Must be the string representation of one of the values from the enum |
| Controls whether constraints are allowed at methods of any kind. Must be set to |
| Controls whether detailed processing information shall be displayed or not, useful for debugging purposes. Must be either |
This section shows in detail how to integrate the Hibernate Validator Annotation Processor intocommand line builds (javac, Ant, Maven) as well as IDE-based builds (Eclipse, IntelliJ IDEA,NetBeans).
When compiling on the command line usingjavac, specify the JARhibernate-validator-annotation-processor-5.2.5.Final.jar using the "processorpath" option as shown inthe following listing. The processor will be detected automatically by the compiler and invokedduring compilation.
Example 12.1. Using the annotation processor with javac
javac src/main/java/org/hibernate/validator/ap/demo/Car.java \ -cp /path/to/validation-api-1.1.0.Final.jar \ -processorpath /path/to/hibernate-validator-annotation-processor-5.2.5.Final.jar
Similar to directly working with javac, the annotation processor can be added as as compilerargument when invoking thejavac taskforApache Ant:
Example 12.2. Using the annotation processor with An
<javac srcdir="src/main" destdir="build/classes" classpath="/path/to/validation-api-1.1.0.Final.jar"> <compilerarg value="-processorpath" /> <compilerarg value="/path/to/hibernate-validator-annotation-processor-5.2.5.Final.jar"/></javac>There are several options for integrating the annotation processor withApache Maven. Generally it is sufficient to add the HibernateValidator Annotation Processor as dependency to your project:
Example 12.3. Adding the HV Annotation Processor as dependency
...<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator-annotation-processor</artifactId> <version>5.2.5.Final</version></dependency>...The processor will then be executed automatically by the compiler. This basically works, but comeswith the disadavantage that in some cases messages from the annotation processor are not displayed(seeMCOMPILER-66).
Another option is using theMaven Annotation Plugin.To work with this plugin, disable the standard annotation processing performedby the compiler plugin and configure the annotation plugin by specifying an execution and adding theHibernate Validator Annotation Processor as plugin dependency (that way the processor is not visibleon the project’s actual classpath):
Example 12.4. Configuring the Maven Annotation Plugin
...<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-proc:none</compilerArgument> </configuration></plugin><plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>process</id> <goals> <goal>process</goal> </goals> <phase>process-sources</phase> </execution> </executions> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator-annotation-processor</artifactId> <version>5.2.5.Final</version> </dependency> </dependencies></plugin>...Do the following to use the annotation processor within theEclipse IDE:
You now should see any annotation problems as regular error markers within the editor and in the"Problem" view:

The following steps must be followed to use the annotation processor withinIntelliJ IDEA (version 9 and above):
Rebuilding your project then should show any erronous constraint annotations:

Starting with version 6.9, also theNetBeans IDE supports usingannotation processors within the IDE build. To do so, do the following:
Any constraint annotation problems will then be marked directly within the editor:

The following known issues exist as of May 2010:
Last but not least, a few pointers to further information.
A great source for examples is the Bean Validation TCK which is available for anonymous access onGitHub. In particular the TCK’stests might beof interest.The JSR 349 specification itselfis also a great way to deepen your understanding of Bean Validation resp. Hibernate Validator.
If you have any further questions to Hibernate Validator or want to share some of your use caseshave a look at theHibernate ValidatorWiki and theHibernate Validator Forum.
In case you would like to report a bug useHibernate’s Jira instance.Feedback is always welcome!