<commit_before>[[chapter-bean-constraints]]
== Declaring and validating bean constraints

In this chapter you will learn how to declare (see <<section-declaring-bean-constraints>>) and
validate (see <<section-validating-bean-constraints>>) bean constraints.
<<section-builtin-constraints>> provides an overview of all built-in constraints coming with
Hibernate Validator.

If you are interested in applying constraints to method parameters and return values, refer to
<<chapter-method-constraints>>.

[[section-declaring-bean-constraints]]
=== Declaring bean constraints

Constraints in Bean Validation are expressed via Java annotations. In this section you will learn
how to enhance an object model with these annotations. There are the following three types of bean
constraints:

* field constraints
* property constraints
* class constraints

[NOTE]
====
Not all constraints can be placed on all of these levels. In fact, none of the default constraints
defined by Bean Validation can be placed at class level. The `java.lang.annotation.Target` annotation
in the constraint annotation itself determines on which elements a constraint can be placed. See
<<validator-customconstraints>> for more information.
====

==== Field-level constraints

Constraints can be expressed by annotating a field of a class. <<example-field-level>> shows a field
level configuration example:

[[example-field-level]]
.Field-level constraints
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/fieldlevel/Car.java[tags=include]
----
====

When using field-level constraints field access strategy is used to access the value to be
validated. This means the validation engine directly accesses the instance variable and does not
invoke the property accessor method even if such an accessor exists.

Constraints can be applied to fields of any access type (public, private etc.). Constraints on
static fields are not supported, though.

[TIP]
====
When validating byte code enhanced objects property level constraints should be used, because the
byte code enhancing library won't be able to determine a field access via reflection.
====

==== Property-level constraints

If your model class adheres to the
http://www.oracle.com/technetwork/articles/javaee/spec-136004.html[JavaBeans] standard, it
is also possible to annotate the properties of a bean class instead of its fields.
<<example-property-level>> uses the same entity as in <<example-field-level>>, however, property level
constraints are used.

[[example-property-level]]
.Property-level constraints
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/propertylevel/Car.java[tags=include]
----
====

[NOTE]
====
The property's getter method has to be annotated, not its setter. That way also read-only properties
can be constrained which have no setter method.
====

When using property level constraints property access strategy is used to access the value to be
validated, i.e. the validation engine accesses the state via the property accessor method.

[TIP]
====
It is recommended to stick either to field _or_ property annotations within one class. It is not
recommended to annotate a field _and_ the accompanying getter method as this would cause the field
to be validated twice.
====

[[type-arguments-constraints]]
==== Type argument constraints

Starting from Java 8, it is possible to specify constraints directly on the type argument of a
parameterized type. This requires that `ElementType.TYPE_USE` is specified via `@Target`
in the constraint definition. As of Bean Validation 2.0, built-in Bean Validation as well as
Hibernate Validator specific constraints specify `ElementType.TYPE_USE` and can be used
directly in this context.

Hibernate Validator validates type arguments constraints specified on collections, map values,
`java.util.Optional`, and custom parameterized types.

===== With `Iterable`

When applying constraints on an `Iterable` type argument, Hibernate Validator will validate each
element. <<example-type-arguments-constraints-collections>> shows an example of a
`List` with a type argument constraint.

In this example, `@ValidPart` is a custom constraint allowed to be used in the `TYPE_USE` context.

[[example-type-arguments-constraints-collections]]
.Type argument constraint on `List`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/list/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/list/CarTest.java[tags=validateListTypeArgumentConstraint]
----
====

===== With `Map`

Type argument constraints are also validated for map values. Constraints on the key are ignored.
<<example-type-arguments-constraints-map>> shows an example of a `Map` value with a type
argument constraint.

[[example-type-arguments-constraints-map]]
.Type argument constraint on maps
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/map/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/map/CarTest.java[tags=validateMapTypeArgumentConstraint]
----
====


===== With `java.util.Optional`

When applying a constraint on the type argument of `Optional`, Hibernate Validator will automatically
unwrap the type and validate the internal value. <<example-type-arguments-constraints-optional>> shows
an example of an `Optional` with a type argument constraint.

[[example-type-arguments-constraints-optional]]
.Type argument constraint on Optional
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/optional/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/optional/CarTest.java[tags=validateOptionalTypeArgumentConstraint]
----
====


===== With custom parameterized types

Type arguments constraints can with two restrictions also be used with custom types. First, a
`ValidatedValueUnwrapper` must be registered for the custom type allowing to retrieve
the value to validate (see <<section-value-handling>>). Second, only types with one type arguments
are supported. Parameterized types with two or more type arguments are not checked for type argument
constraints. This limitation might change in future versions.

<<example-type-arguments-constraints-custom-parameterized-type>> shows an example of a custom
parameterized type with a type argument constraint.

[[example-type-arguments-constraints-custom-parameterized-type]]
.Type argument constraint on custom parameterized type
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/GearBox.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/Gear.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/GearBoxUnwrapper.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/CarTest.java[tags=validateCustomTypeArgumentConstraint]
----
====


[[validator-usingvalidator-classlevel]]
==== Class-level constraints

Last but not least, a constraint can also be placed on the class level. In this case not a single
property is subject of the validation but the complete object. Class-level constraints are useful if
the validation depends on a correlation between several properties of an object.

The Car class in <<example-class-level>> has the two attributes `seatCount` and `passengers` and it
should be ensured that the list of passengers has not more entries than seats are available. For
that purpose the `@ValidPassengerCount` constraint is added on the class level. The validator of that
constraint has access to the complete `Car` object, allowing to compare the numbers of seats and
passengers.

Refer to <<section-class-level-constraints>> to learn in detail how to implement this custom
constraint.

[[example-class-level]]
.Class-level constraint
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/classlevel/Car.java[tags=include]
----
====

[[section-constraint-inheritance]]
==== Constraint inheritance

When a class implements an interface or extends another class, all constraint annotations declared
on the super-type apply in the same manner as the constraints specified on the class itself. To make
things clearer let's have a look at the following example:

.Constraint inheritance
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/inheritance/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/inheritance/RentalCar.java[tags=include]
----
====

Here the class `RentalCar` is a subclass of `Car` and adds the property `rentalStation`. If an instance of
`RentalCar` is validated, not only the `@NotNull` constraint on `rentalStation` is evaluated, but also the
constraint on `manufacturer` from the parent class.

The same would be true, if `Car` was not a superclass but an interface implemented by `RentalCar`.

Constraint annotations are aggregated if methods are overridden. So if `RentalCar` overrode the
`getManufacturer()` method from `Car`, any constraints annotated at the overriding method would be
evaluated in addition to the `@NotNull` constraint from the superclass.

[[section-object-graph-validation]]
==== Object graphs

The Bean Validation API does not only allow to validate single class instances but also complete
object graphs (cascaded validation). To do so, just annotate a field or property representing a
reference to another object with `@Valid` as demonstrated in <<example-cascaded-validation>>.

[[example-cascaded-validation]]
.Cascaded validation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/objectgraph/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/objectgraph/Person.java[tags=include]
----
====

If an instance of `Car` is validated, the referenced `Person` object will be validated as well, as the
`driver` field is annotated with `@Valid`. Therefore the validation of a `Car` will fail if the `name` field
of the referenced `Person` instance is `null`.

The validation of object graphs is recursive, i.e. if a reference marked for cascaded validation
points to an object which itself has properties annotated with `@Valid`, these references will be
followed up by the validation engine as well. The validation engine will ensure that no infinite
loops occur during cascaded validation, for example if two objects hold references to each other.

Note that `null` values are getting ignored during cascaded validation.

Object graph validation also works for collection-typed fields. That means any attributes that


* are arrays
* implement `java.lang.Iterable` (especially `Collection`, `List` and `Set`)
* implement `java.util.Map`

can be annotated with `@Valid`, which will cause each contained element to be validated, when the
parent object is validated.

[[example-cascaded-validation-list]]
.Cascaded validation of a collection
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/objectgraph/list/Car.java[tags=include]
----
====

So when validating an instance of the `Car` class shown in <<example-cascaded-validation-list>>, a
`ConstraintViolation` will be created, if any of the `Person` objects contained in the passengers list
has a `null` name.

[[section-validating-bean-constraints]]
=== Validating bean constraints

The `Validator` interface is the most important object in Bean Validation. The next section shows how
to obtain an `Validator` instance. Afterwards you'll learn how to use the different methods of the
`Validator` interface.

[[section-obtaining-validator]]
==== Obtaining a `Validator` instance

The first step towards validating an entity instance is to get hold of a `Validator` instance. The
road to this instance leads via the `Validation` class and a `ValidatorFactory`. The easiest way is to
use the static method `Validation#buildDefaultValidatorFactory()`:

.`Validation#buildDefaultValidatorFactory()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=setUpValidator]
----
====

This bootstraps a validator in the default configuration. Refer to <<chapter-bootstrapping>> to
learn more about the different bootstrapping methods and how to obtain a specifically configured
`Validator` instance.

==== Validator methods

The `Validator` interface contains three methods that can be used to either validate entire entities
or just single properties of the entity.

All three methods return a `Set<ConstraintViolation>`. The set is empty, if the validation succeeds.
Otherwise a `ConstraintViolation` instance is added for each violated constraint.

All the validation methods have a var-args parameter which can be used to specify, which validation
groups shall be considered when performing the validation. If the parameter is not specified the
default validation group (`javax.validation.groups.Default`) is used. The topic of validation groups
is discussed in detail in <<chapter-groups>>.

===== `Validator#validate()`

Use the `validate()` method to perform validation of all constraints of a given bean.
<<example-validator-validate>> shows the validation of an instance of the `Car` class from
<<example-property-level>> which fails to satisfy the `@NotNull` constraint on the `manufacturer`
property. The validation call therefore returns one `ConstraintViolation` object.

[[example-validator-validate]]
.Using `Validator#validate()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=validate]
----
====


===== `Validator#validateProperty()`

With help of the `validateProperty()` you can validate a single named property of a given object. The
property name is the JavaBeans property name.

.Using `Validator#validateProperty()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=validateProperty]
----
====


===== `Validator#validateValue()`

By using the `validateValue()` method you can check whether a single property of a given class can be
validated successfully, if the property had the specified value:

.Using `Validator#validateValue()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=validateValue]
----
====

[NOTE]
====
`@Valid` is not honored by `validateProperty()` or `validateValue()`.
====


`Validator#validateProperty()` is for example used in the integration of Bean Validation into JSF 2
(see <<section-presentation-layer>>) to perform a validation of the values entered into a form
before they are propagated to the model.

[[section-constraint-violation-methods]]

==== `ConstraintViolation` methods

Now it is time to have a closer look at what a `ConstraintViolation` is. Using the different methods
of `ConstraintViolation` a lot of useful information about the cause of the validation failure can be
determined. <<table-constraint-violation>> gives an overview of these methods. The values in the
"Example" column refer to <<example-validator-validate>>.

[[table-constraint-violation]]
.The various `ConstraintViolation` methods
[options="header"]
|===============
|Method|Usage|Example
|`getMessage()`|The interpolated error message|"may not be null"
|`getMessageTemplate()`|The non-interpolated error message|"{... NotNull.message}"
|`getRootBean()`|The root bean being validated|car
|`getRootBeanClass()`|The class of the root bean being validated|`Car.class`
|`getLeafBean()`|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|`car`
|`getPropertyPath()`|The property path to the validated value from root
              bean|contains one node with kind
              `PROPERTY` and name "manufacturer"
|`getInvalidValue()`|The value failing to pass the constraint|`null`
|`getConstraintDescriptor()`|Constraint metadata reported to fail|descriptor for `@NotNull`

|===============


[[section-builtin-constraints]]
=== Built-in constraints

Hibernate Validator comprises a basic set of commonly used constraints. These are foremost the
constraints defined by the Bean Validation specification (see <<table-spec-constraints>>).
Additionally, Hibernate Validator provides useful custom constraints (see
<<table-custom-constraints>> and <<table-custom-country-constraints>>).

[[validator-defineconstraints-spec]]
==== Bean Validation constraints

<<table-spec-constraints>> shows purpose and supported data types of all constraints specified in
the Bean Validation API. All these constraints apply to the field/property level, there are no
class-level constraints defined in the Bean Validation specification. If you are using the Hibernate
object-relational mapper, some of the constraints are taken into account when creating the DDL for
your model (see column "Hibernate metadata impact").


[NOTE]
====
Hibernate Validator allows some constraints to be applied to more data types than required by the
Bean Validation specification (e.g. `@Max` can be applied to strings). Relying on this feature can
impact portability of your application between Bean Validation providers.
====


[[table-spec-constraints]]
.Bean Validation constraints
[options="header"]
|===============
|Annotation|Supported data types|Use|Hibernate metadata impact
|`@AssertFalse`|`Boolean`,
              `boolean`|Checks that the annotated element is
              false|None
|`@AssertTrue`|`Boolean`,
              `boolean`|Checks that the annotated element is
              true|None
|`@DecimalMax(value=,inclusive=)`|`BigDecimal`,
              `BigInteger`,
              `CharSequence`,
              `byte`, `short`,
              `int`, `long` and the
              respective wrappers of the primitive types; Additionally
              supported by HV: any sub-type of
              `Number` and `javax.money.MonetaryAmount`|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<commit_msg>HV-1116 Expanding docs a bit<commit_after>[[chapter-bean-constraints]]
== Declaring and validating bean constraints

In this chapter you will learn how to declare (see <<section-declaring-bean-constraints>>) and
validate (see <<section-validating-bean-constraints>>) bean constraints.
<<section-builtin-constraints>> provides an overview of all built-in constraints coming with
Hibernate Validator.

If you are interested in applying constraints to method parameters and return values, refer to
<<chapter-method-constraints>>.

[[section-declaring-bean-constraints]]
=== Declaring bean constraints

Constraints in Bean Validation are expressed via Java annotations. In this section you will learn
how to enhance an object model with these annotations. There are the following three types of bean
constraints:

* field constraints
* property constraints
* class constraints

[NOTE]
====
Not all constraints can be placed on all of these levels. In fact, none of the default constraints
defined by Bean Validation can be placed at class level. The `java.lang.annotation.Target` annotation
in the constraint annotation itself determines on which elements a constraint can be placed. See
<<validator-customconstraints>> for more information.
====

==== Field-level constraints

Constraints can be expressed by annotating a field of a class. <<example-field-level>> shows a field
level configuration example:

[[example-field-level]]
.Field-level constraints
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/fieldlevel/Car.java[tags=include]
----
====

When using field-level constraints field access strategy is used to access the value to be
validated. This means the validation engine directly accesses the instance variable and does not
invoke the property accessor method even if such an accessor exists.

Constraints can be applied to fields of any access type (public, private etc.). Constraints on
static fields are not supported, though.

[TIP]
====
When validating byte code enhanced objects property level constraints should be used, because the
byte code enhancing library won't be able to determine a field access via reflection.
====

==== Property-level constraints

If your model class adheres to the
http://www.oracle.com/technetwork/articles/javaee/spec-136004.html[JavaBeans] standard, it
is also possible to annotate the properties of a bean class instead of its fields.
<<example-property-level>> uses the same entity as in <<example-field-level>>, however, property level
constraints are used.

[[example-property-level]]
.Property-level constraints
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/propertylevel/Car.java[tags=include]
----
====

[NOTE]
====
The property's getter method has to be annotated, not its setter. That way also read-only properties
can be constrained which have no setter method.
====

When using property level constraints property access strategy is used to access the value to be
validated, i.e. the validation engine accesses the state via the property accessor method.

[TIP]
====
It is recommended to stick either to field _or_ property annotations within one class. It is not
recommended to annotate a field _and_ the accompanying getter method as this would cause the field
to be validated twice.
====

[[type-arguments-constraints]]
==== Type argument constraints

Starting from Java 8, it is possible to specify constraints directly on the type argument of a
parameterized type. This requires that `ElementType.TYPE_USE` is specified via `@Target`
in the constraint definition. As of Bean Validation 2.0, built-in Bean Validation as well as
Hibernate Validator specific constraints specify `ElementType.TYPE_USE` and can be used
directly in this context.

Hibernate Validator validates type arguments constraints specified on collections, map values,
`java.util.Optional`, and custom parameterized types.

===== With `Iterable`

When applying constraints on an `Iterable` type argument, Hibernate Validator will validate each
element. <<example-type-arguments-constraints-collections>> shows an example of a
`List` with a type argument constraint.

In this example, `@ValidPart` is a custom constraint allowed to be used in the `TYPE_USE` context.

[[example-type-arguments-constraints-collections]]
.Type argument constraint on `List`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/list/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/list/CarTest.java[tags=validateListTypeArgumentConstraint]
----
====

===== With `Map`

Type argument constraints are also validated for map values. Constraints on the key are ignored.
<<example-type-arguments-constraints-map>> shows an example of a `Map` value with a type
argument constraint.

[[example-type-arguments-constraints-map]]
.Type argument constraint on maps
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/map/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/map/CarTest.java[tags=validateMapTypeArgumentConstraint]
----
====


===== With `java.util.Optional`

When applying a constraint on the type argument of `Optional`, Hibernate Validator will automatically
unwrap the type and validate the internal value. <<example-type-arguments-constraints-optional>> shows
an example of an `Optional` with a type argument constraint.

[[example-type-arguments-constraints-optional]]
.Type argument constraint on Optional
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/optional/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/optional/CarTest.java[tags=validateOptionalTypeArgumentConstraint]
----
====


===== With custom parameterized types

Type arguments constraints can with two restrictions also be used with custom types. First, a
`ValidatedValueUnwrapper` must be registered for the custom type allowing to retrieve
the value to validate (see <<section-value-handling>>). Second, only types with one type arguments
are supported. Parameterized types with two or more type arguments are not checked for type argument
constraints. This limitation might change in future versions.

<<example-type-arguments-constraints-custom-parameterized-type>> shows an example of a custom
parameterized type with a type argument constraint.

[[example-type-arguments-constraints-custom-parameterized-type]]
.Type argument constraint on custom parameterized type
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/GearBox.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/Gear.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/GearBoxUnwrapper.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/typeargument/custom/CarTest.java[tags=validateCustomTypeArgumentConstraint]
----
====


[[validator-usingvalidator-classlevel]]
==== Class-level constraints

Last but not least, a constraint can also be placed on the class level. In this case not a single
property is subject of the validation but the complete object. Class-level constraints are useful if
the validation depends on a correlation between several properties of an object.

The Car class in <<example-class-level>> has the two attributes `seatCount` and `passengers` and it
should be ensured that the list of passengers has not more entries than seats are available. For
that purpose the `@ValidPassengerCount` constraint is added on the class level. The validator of that
constraint has access to the complete `Car` object, allowing to compare the numbers of seats and
passengers.

Refer to <<section-class-level-constraints>> to learn in detail how to implement this custom
constraint.

[[example-class-level]]
.Class-level constraint
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/classlevel/Car.java[tags=include]
----
====

[[section-constraint-inheritance]]
==== Constraint inheritance

When a class implements an interface or extends another class, all constraint annotations declared
on the super-type apply in the same manner as the constraints specified on the class itself. To make
things clearer let's have a look at the following example:

.Constraint inheritance
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/inheritance/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/inheritance/RentalCar.java[tags=include]
----
====

Here the class `RentalCar` is a subclass of `Car` and adds the property `rentalStation`. If an instance of
`RentalCar` is validated, not only the `@NotNull` constraint on `rentalStation` is evaluated, but also the
constraint on `manufacturer` from the parent class.

The same would be true, if `Car` was not a superclass but an interface implemented by `RentalCar`.

Constraint annotations are aggregated if methods are overridden. So if `RentalCar` overrode the
`getManufacturer()` method from `Car`, any constraints annotated at the overriding method would be
evaluated in addition to the `@NotNull` constraint from the superclass.

[[section-object-graph-validation]]
==== Object graphs

The Bean Validation API does not only allow to validate single class instances but also complete
object graphs (cascaded validation). To do so, just annotate a field or property representing a
reference to another object with `@Valid` as demonstrated in <<example-cascaded-validation>>.

[[example-cascaded-validation]]
.Cascaded validation
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/objectgraph/Car.java[tags=include]
----

[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/objectgraph/Person.java[tags=include]
----
====

If an instance of `Car` is validated, the referenced `Person` object will be validated as well, as the
`driver` field is annotated with `@Valid`. Therefore the validation of a `Car` will fail if the `name` field
of the referenced `Person` instance is `null`.

The validation of object graphs is recursive, i.e. if a reference marked for cascaded validation
points to an object which itself has properties annotated with `@Valid`, these references will be
followed up by the validation engine as well. The validation engine will ensure that no infinite
loops occur during cascaded validation, for example if two objects hold references to each other.

Note that `null` values are getting ignored during cascaded validation.

Object graph validation also works for collection-typed fields. That means any attributes that


* are arrays
* implement `java.lang.Iterable` (especially `Collection`, `List` and `Set`)
* implement `java.util.Map`

can be annotated with `@Valid`, which will cause each contained element to be validated, when the
parent object is validated.

[[example-cascaded-validation-list]]
.Cascaded validation of a collection
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/objectgraph/list/Car.java[tags=include]
----
====

So when validating an instance of the `Car` class shown in <<example-cascaded-validation-list>>, a
`ConstraintViolation` will be created, if any of the `Person` objects contained in the passengers list
has a `null` name.

[[section-validating-bean-constraints]]
=== Validating bean constraints

The `Validator` interface is the most important object in Bean Validation. The next section shows how
to obtain an `Validator` instance. Afterwards you'll learn how to use the different methods of the
`Validator` interface.

[[section-obtaining-validator]]
==== Obtaining a `Validator` instance

The first step towards validating an entity instance is to get hold of a `Validator` instance. The
road to this instance leads via the `Validation` class and a `ValidatorFactory`. The easiest way is to
use the static method `Validation#buildDefaultValidatorFactory()`:

.`Validation#buildDefaultValidatorFactory()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=setUpValidator]
----
====

This bootstraps a validator in the default configuration. Refer to <<chapter-bootstrapping>> to
learn more about the different bootstrapping methods and how to obtain a specifically configured
`Validator` instance.

==== Validator methods

The `Validator` interface contains three methods that can be used to either validate entire entities
or just single properties of the entity.

All three methods return a `Set<ConstraintViolation>`. The set is empty, if the validation succeeds.
Otherwise a `ConstraintViolation` instance is added for each violated constraint.

All the validation methods have a var-args parameter which can be used to specify, which validation
groups shall be considered when performing the validation. If the parameter is not specified the
default validation group (`javax.validation.groups.Default`) is used. The topic of validation groups
is discussed in detail in <<chapter-groups>>.

===== `Validator#validate()`

Use the `validate()` method to perform validation of all constraints of a given bean.
<<example-validator-validate>> shows the validation of an instance of the `Car` class from
<<example-property-level>> which fails to satisfy the `@NotNull` constraint on the `manufacturer`
property. The validation call therefore returns one `ConstraintViolation` object.

[[example-validator-validate]]
.Using `Validator#validate()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=validate]
----
====


===== `Validator#validateProperty()`

With help of the `validateProperty()` you can validate a single named property of a given object. The
property name is the JavaBeans property name.

.Using `Validator#validateProperty()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=validateProperty]
----
====


===== `Validator#validateValue()`

By using the `validateValue()` method you can check whether a single property of a given class can be
validated successfully, if the property had the specified value:

.Using `Validator#validateValue()`
====
[source, JAVA, indent=0]
----
include::{sourcedir}/org/hibernate/validator/referenceguide/chapter02/validation/ValidationTest.java[tags=validateValue]
----
====

[NOTE]
====
`@Valid` is not honored by `validateProperty()` or `validateValue()`.
====


`Validator#validateProperty()` is for example used in the integration of Bean Validation into JSF 2
(see <<section-presentation-layer>>) to perform a validation of the values entered into a form
before they are propagated to the model.

[[section-constraint-violation-methods]]

==== `ConstraintViolation` methods

Now it is time to have a closer look at what a `ConstraintViolation` is. Using the different methods
of `ConstraintViolation` a lot of useful information about the cause of the validation failure can be
determined. <<table-constraint-violation>> gives an overview of these methods. The values in the
"Example" column refer to <<example-validator-validate>>.

[[table-constraint-violation]]
.The various `ConstraintViolation` methods
[options="header"]
|===============
|Method|Usage|Example
|`getMessage()`|The interpolated error message|"may not be null"
|`getMessageTemplate()`|The non-interpolated error message|"{... NotNull.message}"
|`getRootBean()`|The root bean being validated|car
|`getRootBeanClass()`|The class of the root bean being validated|`Car.class`
|`getLeafBean()`|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|`car`
|`getPropertyPath()`|The property path to the validated value from root
              bean|contains one node with kind
              `PROPERTY` and name "manufacturer"
|`getInvalidValue()`|The value failing to pass the constraint|`null`
|`getConstraintDescriptor()`|Constraint metadata reported to fail|descriptor for `@NotNull`

|===============


[[section-builtin-constraints]]
=== Built-in constraints

Hibernate Validator comprises a basic set of commonly used constraints. These are foremost the
constraints defined by the Bean Validation specification (see <<table-spec-constraints>>).
Additionally, Hibernate Validator provides useful custom constraints (see
<<table-custom-constraints>> and <<table-custom-country-constraints>>).

[[validator-defineconstraints-spec]]
==== Bean Validation constraints

<<table-spec-constraints>> shows purpose and supported data types of all constraints specified in
the Bean Validation API. All these constraints apply to the field/property level, there are no
class-level constraints defined in the Bean Validation specification. If you are using the Hibernate
object-relational mapper, some of the constraints are taken into account when creating the DDL for
your model (see column "Hibernate metadata impact").


[NOTE]
====
Hibernate Validator allows some constraints to be applied to more data types than required by the
Bean Validation specification (e.g. `@Max` can be applied to strings). Relying on this feature can
impact portability of your application between Bean Validation providers.
====


[[table-spec-constraints]]
.Bean Validation constraints
[options="header"]
|===============
|Annotation|Supported data types|Use|Hibernate metadata impact
|`@AssertFalse`|`Boolean`,
              `boolean`|Checks that the annotated element is
              false|None
|`@AssertTrue`|`Boolean`,
              `boolean`|Checks that the annotated element is
              true|None
|`@DecimalMax(value=,inclusive=)`|`BigDecimal`,
              `BigInteger`,
              `CharSequence`,
              `byte`, `short`,
              `int`, `long` and the
              respective wrappers of the primitive types; Additionally
              supported by HV: any sub-type of
              `Number` and `javax.money.MonetaryAmount` (if the https://jcp.org/en/jsr/detail?id=354[JSR 354 API] and an implementation is on the class path)|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
{'fraction_non_alphanumeric': 0.10114125254398845, 'fraction_numerical': 0.004328000618285803, 'mean_word_length': 5.039831958923292, 'pattern_counts': {'":': 0, '<': 117, '<?xml version=': 0, '>': 117, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5517317', 'n_tokens_mistral': 10363, 'n_tokens_neox': 9810, 'n_words': 4072}