| 1 |
[[chapter-bean-constraints]] |
| 2 |
== Declaring and validating bean constraints |
| 3 |
|
| 4 |
In this chapter you will learn how to declare (see <<section-declaring-bean-constraints>>) and |
| 5 |
validate (see <<section-validating-bean-constraints>>) bean constraints. |
| 6 |
<<section-builtin-constraints>> provides an overview of all built-in constraints coming with |
| 7 |
Hibernate Validator. |
| 8 |
|
| 9 |
If you are interested in applying constraints to method parameters and return values, refer to |
| 10 |
<<chapter-method-constraints>>. |
| 11 |
|
| 12 |
[[section-declaring-bean-constraints]] |
| 13 |
=== Declaring bean constraints |
| 14 |
|
| 15 |
Constraints in Bean Validation are expressed via Java annotations. In this section you will learn |
| 16 |
how to enhance an object model with these annotations. There are the following three types of bean |
| 17 |
constraints: |
| 18 |
|
| 19 |
* field constraints |
| 20 |
* property constraints |
| 21 |
* class constraints |
| 22 |
|
| 23 |
[NOTE] |
| 24 |
==== |
| 25 |
Not all constraints can be placed on all of these levels. In fact, none of the default constraints |
| 26 |
defined by Bean Validation can be placed at class level. The `java.lang.annotation.Target` annotation |
| 27 |
in the constraint annotation itself determines on which elements a constraint can be placed. See |
| 28 |
<<validator-customconstraints>> for more information. |
| 29 |
==== |
| 30 |
|
| 31 |
==== Field-level constraints |
| 32 |
|
| 33 |
Constraints can be expressed by annotating a field of a class. <<example-field-level>> shows a field |
| 34 |
level configuration example: |
| 35 |
|
| 36 |
[[example-field-level]] |
| 37 |
.Field-level constraints |
| 38 |
==== |
| 39 |
[source, JAVA] |
| 40 |
---- |
| 41 |
package org.hibernate.validator.referenceguide.chapter02.fieldlevel; |
| 42 |
|
| 43 |
public class Car { |
| 44 |
|
| 45 |
@NotNull |
| 46 |
private String manufacturer; |
| 47 |
|
| 48 |
@AssertTrue |
| 49 |
private boolean isRegistered; |
| 50 |
|
| 51 |
public Car(String manufacturer, boolean isRegistered) { |
| 52 |
this.manufacturer = manufacturer; |
| 53 |
this.isRegistered = isRegistered; |
| 54 |
} |
| 55 |
|
| 56 |
//getters and setters... |
| 57 |
} |
| 58 |
---- |
| 59 |
==== |
| 60 |
|
| 61 |
When using field-level constraints field access strategy is used to access the value to be |
| 62 |
validated. This means the validation engine directly accesses the instance variable and does not |
| 63 |
invoke the property accessor method even if such an accessor exists. |
| 64 |
|
| 65 |
Constraints can be applied to fields of any access type (public, private etc.). Constraints on |
| 66 |
static fields are not supported, though. |
| 67 |
|
| 68 |
[TIP] |
| 69 |
==== |
| 70 |
When validating byte code enhanced objects property level constraints should be used, because the |
| 71 |
byte code enhancing library won't be able to determine a field access via reflection. |
| 72 |
==== |
| 73 |
|
| 74 |
==== Property-level constraints |
| 75 |
|
| 76 |
If your model class adheres to the |
| 77 |
http://java.sun.com/javase/technologies/desktop/javabeans/index.jsp[JavaBeans] standard, it |
| 78 |
is also possible to annotate the properties of a bean class instead of its fields. |
| 79 |
<<example-property-level>> uses the same entity as in <<example-field-level>>, however, property level |
| 80 |
constraints are used. |
| 81 |
|
| 82 |
[[example-property-level]] |
| 83 |
.Property-level constraints |
| 84 |
==== |
| 85 |
[source, JAVA] |
| 86 |
---- |
| 87 |
package org.hibernate.validator.referenceguide.chapter02.propertylevel; |
| 88 |
|
| 89 |
public class Car { |
| 90 |
|
| 91 |
private String manufacturer; |
| 92 |
|
| 93 |
private boolean isRegistered; |
| 94 |
|
| 95 |
public Car(String manufacturer, boolean isRegistered) { |
| 96 |
this.manufacturer = manufacturer; |
| 97 |
this.isRegistered = isRegistered; |
| 98 |
} |
| 99 |
|
| 100 |
@NotNull |
| 101 |
public String getManufacturer() { |
| 102 |
return manufacturer; |
| 103 |
} |
| 104 |
|
| 105 |
public void setManufacturer(String manufacturer) { |
| 106 |
this.manufacturer = manufacturer; |
| 107 |
} |
| 108 |
|
| 109 |
@AssertTrue |
| 110 |
public boolean isRegistered() { |
| 111 |
return isRegistered; |
| 112 |
} |
| 113 |
|
| 114 |
public void setRegistered(boolean isRegistered) { |
| 115 |
this.isRegistered = isRegistered; |
| 116 |
} |
| 117 |
} |
| 118 |
---- |
| 119 |
==== |
| 120 |
|
| 121 |
[NOTE] |
| 122 |
==== |
| 123 |
The property's getter method has to be annotated, not its setter. That way also read-only properties |
| 124 |
can be constrained which have no setter method. |
| 125 |
==== |
| 126 |
|
| 127 |
When using property level constraints property access strategy is used to access the value to be |
| 128 |
validated, i.e. the validation engine accesses the state via the property accessor method. |
| 129 |
|
| 130 |
[TIP] |
| 131 |
==== |
| 132 |
It is recommended to stick either to field _or_ property annotations within one class. It is not |
| 133 |
recommended to annotate a field _and_ the accompanying getter method as this would cause the field |
| 134 |
to be validated twice. |
| 135 |
==== |
| 136 |
|
| 137 |
[[type-arguments-constraints]] |
| 138 |
==== Type argument constraints |
| 139 |
|
| 140 |
Starting from Java 8, it is possible to specify constraints directly on the type argument of a |
| 141 |
parameterized type. However, this requires that `ElementType.TYPE_USE` is specified via `@Target` |
| 142 |
in the constraint definition. To maintain backwards compatibility, built-in Bean Validation as well as |
| 143 |
Hibernate Validator specific constraints do not yet specify `ElementType.TYPE_USE`. To make use of |
| 144 |
type argument constraints, custom constraints must be used (see <<validator-customconstraints>>). |
| 145 |
|
| 146 |
Hibernate Validator validates type arguments constraints specified on collections, map values, |
| 147 |
`java.util.Optional`, and custom parameterized types. |
| 148 |
|
| 149 |
===== With `Iterable` |
| 150 |
|
| 151 |
When applying constraints on an `Iterable` type argument, Hibernate Validator will validate each |
| 152 |
element. <<example-type-arguments-constraints-collections>> shows an example of a |
| 153 |
`List` with a type argument constraint. |
| 154 |
|
| 155 |
In this example, `@ValidPart` is a custom constraint allowed to be used in the `TYPE_USE` context. |
| 156 |
|
| 157 |
[[example-type-arguments-constraints-collections]] |
| 158 |
.Type argument constraint on `List` |
| 159 |
==== |
| 160 |
[source, JAVA] |
| 161 |
---- |
| 162 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 163 |
|
| 164 |
public class Car { |
| 165 |
|
| 166 |
@Valid |
| 167 |
private List<@ValidPart String> parts = new ArrayList<>(); |
| 168 |
|
| 169 |
public void addPart(String part) { |
| 170 |
parts.add( part ); |
| 171 |
} |
| 172 |
|
| 173 |
//... |
| 174 |
} |
| 175 |
---- |
| 176 |
|
| 177 |
[source, JAVA] |
| 178 |
---- |
| 179 |
Car car = Car(); |
| 180 |
car.addPart( "Wheel" ); |
| 181 |
car.addPart( null ); |
| 182 |
|
| 183 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); |
| 184 |
|
| 185 |
assertEquals( 1, constraintViolations.size() ); |
| 186 |
assertEquals( |
| 187 |
"'null' is not a valid car part.", |
| 188 |
constraintViolations.iterator().next().getMessage() |
| 189 |
); |
| 190 |
assertEquals( "parts[1].<collection element>", |
| 191 |
constraintViolations.iterator().next().getPropertyPath().toString() ); |
| 192 |
---- |
| 193 |
==== |
| 194 |
|
| 195 |
===== With `Map` |
| 196 |
|
| 197 |
Type argument constraints are also validated for map values. Constraints on the key are ignored. |
| 198 |
<<example-type-arguments-constraints-map>> shows an example of a `Map` value with a type |
| 199 |
argument constraint. |
| 200 |
|
| 201 |
[[example-type-arguments-constraints-map]] |
| 202 |
.Type argument constraint on maps |
| 203 |
==== |
| 204 |
[source, JAVA] |
| 205 |
---- |
| 206 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 207 |
|
| 208 |
public class Car { |
| 209 |
|
| 210 |
public static enum FuelConsumption { |
| 211 |
CITY, |
| 212 |
HIGHWAY |
| 213 |
} |
| 214 |
|
| 215 |
@Valid |
| 216 |
private EnumMap<FuelConsumption, @MaxAllowedFuelConsumption Integer> fuelConsumption = new EnumMap<>( FuelConsumption.class ); |
| 217 |
|
| 218 |
public void setFuelConsumption(FuelConsumption consumption, int value) { |
| 219 |
fuelConsumption.put( consumption, value ); |
| 220 |
} |
| 221 |
|
| 222 |
//... |
| 223 |
} |
| 224 |
|
| 225 |
---- |
| 226 |
|
| 227 |
[source, JAVA] |
| 228 |
---- |
| 229 |
Car car = new Car(); |
| 230 |
car.setFuelConsumption( Car.FuelConsumption.HIGHWAY, 20 ); |
| 231 |
|
| 232 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); |
| 233 |
|
| 234 |
assertEquals( 1, constraintViolations.size() ); |
| 235 |
assertEquals( "20 is outside the max fuel consumption.", constraintViolations.iterator().next().getMessage() ); |
| 236 |
---- |
| 237 |
==== |
| 238 |
|
| 239 |
|
| 240 |
===== With `java.util.Optional` |
| 241 |
|
| 242 |
When applying a constraint on the type argument of `Optional`, Hibernate Validator will automatically |
| 243 |
unwrap the type and validate the internal value. <<example-type-arguments-constraints-optional>> shows |
| 244 |
an example of an `Optional` with a type argument constraint. |
| 245 |
|
| 246 |
[[example-type-arguments-constraints-optional]] |
| 247 |
.Type argument constraint on Optional |
| 248 |
==== |
| 249 |
[source, JAVA] |
| 250 |
---- |
| 251 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 252 |
|
| 253 |
import java.util.ArrayList; |
| 254 |
import java.util.EnumMap; |
| 255 |
import java.util.List; |
| 256 |
import java.util.Optional; |
| 257 |
import javax.validation.Valid; |
| 258 |
|
| 259 |
public class Car { |
| 260 |
|
| 261 |
private Optional<@MinTowingCapacity(1000) Integer> towingCapacity = Optional.empty(); |
| 262 |
|
| 263 |
public void setTowingCapacity(Integer alias) { |
| 264 |
towingCapacity = Optional.of( alias ); |
| 265 |
} |
| 266 |
|
| 267 |
//... |
| 268 |
} |
| 269 |
|
| 270 |
---- |
| 271 |
|
| 272 |
[source, JAVA] |
| 273 |
---- |
| 274 |
Car car = Car(); |
| 275 |
car.setTowingCapacity( 100 ); |
| 276 |
|
| 277 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); |
| 278 |
|
| 279 |
assertEquals( 1, constraintViolations.size() ); |
| 280 |
assertEquals( "Not enough towing capacity.", constraintViolations.iterator().next().getMessage() ); |
| 281 |
assertEquals( "towingCapacity", constraintViolations.iterator().next().getPropertyPath().toString() ); |
| 282 |
---- |
| 283 |
==== |
| 284 |
|
| 285 |
|
| 286 |
===== With custom parameterized types |
| 287 |
|
| 288 |
Type arguments constraints can with two restrictions also be used with custom types. First, a |
| 289 |
`ValidatedValueUnwrapper` must be registered for the custom type allowing to retrieve |
| 290 |
the value to validate (see <<section-value-handling>>). Second, only types with one type arguments |
| 291 |
are supported. Parameterized types with two or more type arguments are not checked for type argument |
| 292 |
constraints. This limitation might change in future versions. |
| 293 |
|
| 294 |
<<example-type-arguments-constraints-custom-parameterized-type>> shows an example of a custom |
| 295 |
parameterized type with a type argument constraint. |
| 296 |
|
| 297 |
[[example-type-arguments-constraints-custom-parameterized-type]] |
| 298 |
.Type argument constraint on custom parameterized type |
| 299 |
==== |
| 300 |
[source, JAVA] |
| 301 |
---- |
| 302 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 303 |
|
| 304 |
public class Car { |
| 305 |
|
| 306 |
private GearBox<@MinTorque(100) Gear> gearBox; |
| 307 |
|
| 308 |
public void setGearBox(GearBox<Gear> gearBox) { |
| 309 |
this.gearBox = gearBox; |
| 310 |
} |
| 311 |
|
| 312 |
//... |
| 313 |
} |
| 314 |
|
| 315 |
---- |
| 316 |
|
| 317 |
[source, JAVA] |
| 318 |
---- |
| 319 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 320 |
|
| 321 |
public class GearBox<T extends Gear> { |
| 322 |
|
| 323 |
private final T gear; |
| 324 |
|
| 325 |
public GearBox(T gear) { |
| 326 |
this.gear = gear; |
| 327 |
} |
| 328 |
|
| 329 |
public Gear getGear() { |
| 330 |
return this.gear; |
| 331 |
} |
| 332 |
} |
| 333 |
---- |
| 334 |
|
| 335 |
[source, JAVA] |
| 336 |
---- |
| 337 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 338 |
|
| 339 |
public class Gear { |
| 340 |
private final Integer torque; |
| 341 |
|
| 342 |
public Gear(Integer torque) { |
| 343 |
this.torque = torque; |
| 344 |
} |
| 345 |
|
| 346 |
public Integer getTorque() { |
| 347 |
return torque; |
| 348 |
} |
| 349 |
|
| 350 |
public static class AcmeGear extends Gear { |
| 351 |
public AcmeGear() { |
| 352 |
super( 100 ); |
| 353 |
} |
| 354 |
} |
| 355 |
} |
| 356 |
---- |
| 357 |
|
| 358 |
[source, JAVA] |
| 359 |
---- |
| 360 |
package org.hibernate.validator.referenceguide.chapter02.typeargument; |
| 361 |
|
| 362 |
public class GearBoxUnwrapper extends ValidatedValueUnwrapper<GearBox> { |
| 363 |
@Override |
| 364 |
public Object handleValidatedValue(GearBox gearBox) { |
| 365 |
return gearBox == null ? null : gearBox.getGear(); |
| 366 |
} |
| 367 |
|
| 368 |
@Override |
| 369 |
public Type getValidatedValueType(Type valueType) { |
| 370 |
return Gear.class; |
| 371 |
} |
| 372 |
} |
| 373 |
---- |
| 374 |
|
| 375 |
[source, JAVA] |
| 376 |
---- |
| 377 |
Car car = Car(); |
| 378 |
car.setGearBox( new GearBox<>( new Gear.AcmeGear() ) ); |
| 379 |
|
| 380 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); |
| 381 |
assertEquals( 1, constraintViolations.size() ); |
| 382 |
assertEquals( "Gear is not providing enough torque.", constraintViolations.iterator().next().getMessage() ); |
| 383 |
assertEquals( "gearBox", constraintViolations.iterator().next().getPropertyPath().toString() ); |
| 384 |
---- |
| 385 |
==== |
| 386 |
|
| 387 |
|
| 388 |
[[validator-usingvalidator-classlevel]] |
| 389 |
==== Class-level constraints |
| 390 |
|
| 391 |
Last but not least, a constraint can also be placed on the class level. In this case not a single |
| 392 |
property is subject of the validation but the complete object. Class-level constraints are useful if |
| 393 |
the validation depends on a correlation between several properties of an object. |
| 394 |
|
| 395 |
The Car class in <<example-class-level>> has the two attributes `seatCount` and `passengers` and it |
| 396 |
should be ensured that the list of passengers has not more entries than seats are available. For |
| 397 |
that purpose the `@ValidPassengerCount` constraint is added on the class level. The validator of that |
| 398 |
constraint has access to the complete `Car` object, allowing to compare the numbers of seats and |
| 399 |
passengers. |
| 400 |
|
| 401 |
Refer to <<section-class-level-constraints>> to learn in detail how to implement this custom |
| 402 |
constraint. |
| 403 |
|
| 404 |
[[example-class-level]] |
| 405 |
.Class-level constraint |
| 406 |
==== |
| 407 |
[source, JAVA] |
| 408 |
---- |
| 409 |
package org.hibernate.validator.referenceguide.chapter02.classlevel; |
| 410 |
|
| 411 |
@ValidPassengerCount |
| 412 |
public class Car { |
| 413 |
|
| 414 |
private int seatCount; |
| 415 |
|
| 416 |
private List<Person> passengers; |
| 417 |
|
| 418 |
//... |
| 419 |
} |
| 420 |
---- |
| 421 |
==== |
| 422 |
|
| 423 |
[[section-constraint-inheritance]] |
| 424 |
==== Constraint inheritance |
| 425 |
|
| 426 |
When a class implements an interface or extends another class, all constraint annotations declared |
| 427 |
on the super-type apply in the same manner as the constraints specified on the class itself. To make |
| 428 |
things clearer let's have a look at the following example: |
| 429 |
|
| 430 |
.Constraint inheritance |
| 431 |
==== |
| 432 |
[source, JAVA] |
| 433 |
---- |
| 434 |
package org.hibernate.validator.referenceguide.chapter02.inheritance; |
| 435 |
|
| 436 |
public class Car { |
| 437 |
|
| 438 |
private String manufacturer; |
| 439 |
|
| 440 |
@NotNull |
| 441 |
public String getManufacturer() { |
| 442 |
return manufacturer; |
| 443 |
} |
| 444 |
|
| 445 |
//... |
| 446 |
} |
| 447 |
---- |
| 448 |
|
| 449 |
[source, JAVA] |
| 450 |
---- |
| 451 |
package org.hibernate.validator.referenceguide.chapter02.inheritance; |
| 452 |
|
| 453 |
public class RentalCar extends Car { |
| 454 |
|
| 455 |
private String rentalStation; |
| 456 |
|
| 457 |
@NotNull |
| 458 |
public String getRentalStation() { |
| 459 |
return rentalStation; |
| 460 |
} |
| 461 |
|
| 462 |
//... |
| 463 |
} |
| 464 |
---- |
| 465 |
==== |
| 466 |
|
| 467 |
Here the class `RentalCar` is a subclass of `Car` and adds the property `rentalStation`. If an instance of |
| 468 |
`RentalCar` is validated, not only the `@NotNull` constraint on `rentalStation` is evaluated, but also the |
| 469 |
constraint on `manufacturer` from the parent class. |
| 470 |
|
| 471 |
The same would be true, if `Car` was not a superclass but an interface implemented by `RentalCar`. |
| 472 |
|
| 473 |
Constraint annotations are aggregated if methods are overridden. So if `RentalCar` overrode the |
| 474 |
`getManufacturer()` method from `Car`, any constraints annotated at the overriding method would be |
| 475 |
evaluated in addition to the `@NotNull` constraint from the superclass. |
| 476 |
|
| 477 |
[[section-object-graph-validation]] |
| 478 |
==== Object graphs |
| 479 |
|
| 480 |
The Bean Validation API does not only allow to validate single class instances but also complete |
| 481 |
object graphs (cascaded validation). To do so, just annotate a field or property representing a |
| 482 |
reference to another object with `@Valid` as demonstrated in <<example-cascaded-validation>>. |
| 483 |
|
| 484 |
[[example-cascaded-validation]] |
| 485 |
.Cascaded validation |
| 486 |
==== |
| 487 |
[source, JAVA] |
| 488 |
---- |
| 489 |
package org.hibernate.validator.referenceguide.chapter02.objectgraph; |
| 490 |
|
| 491 |
public class Car { |
| 492 |
|
| 493 |
@NotNull |
| 494 |
@Valid |
| 495 |
private Person driver; |
| 496 |
|
| 497 |
//... |
| 498 |
} |
| 499 |
---- |
| 500 |
|
| 501 |
[source, JAVA] |
| 502 |
---- |
| 503 |
package org.hibernate.validator.referenceguide.chapter02.objectgraph; |
| 504 |
|
| 505 |
public class Person { |
| 506 |
|
| 507 |
@NotNull |
| 508 |
private String name; |
| 509 |
|
| 510 |
//... |
| 511 |
} |
| 512 |
---- |
| 513 |
==== |
| 514 |
|
| 515 |
If an instance of `Car` is validated, the referenced `Person` object will be validated as well, as the |
| 516 |
`driver` field is annotated with `@Valid`. Therefore the validation of a `Car` will fail if the `name` field |
| 517 |
of the referenced `Person` instance is `null`. |
| 518 |
|
| 519 |
The validation of object graphs is recursive, i.e. if a reference marked for cascaded validation |
| 520 |
points to an object which itself has properties annotated with `@Valid`, these references will be |
| 521 |
followed up by the validation engine as well. The validation engine will ensure that no infinite |
| 522 |
loops occur during cascaded validation, for example if two objects hold references to each other. |
| 523 |
|
| 524 |
Note that `null` values are getting ignored during cascaded validation. |
| 525 |
|
| 526 |
Object graph validation also works for collection-typed fields. That means any attributes that |
| 527 |
|
| 528 |
|
| 529 |
* are arrays |
| 530 |
* implement `java.lang.Iterable` (especially `Collection`, `List` and `Set`) |
| 531 |
* implement `java.util.Map` |
| 532 |
|
| 533 |
can be annotated with `@Valid`, which will cause each contained element to be validated, when the |
| 534 |
parent object is validated. |
| 535 |
|
| 536 |
[[example-cascaded-validation-list]] |
| 537 |
.Cascaded validation of a collection |
| 538 |
==== |
| 539 |
[source, JAVA] |
| 540 |
---- |
| 541 |
package org.hibernate.validator.referenceguide.chapter02.objectgraph.list; |
| 542 |
|
| 543 |
public class Car { |
| 544 |
|
| 545 |
@NotNull |
| 546 |
@Valid |
| 547 |
private List<Person> passengers = new ArrayList<Person>(); |
| 548 |
|
| 549 |
//... |
| 550 |
} |
| 551 |
---- |
| 552 |
==== |
| 553 |
|
| 554 |
So when validating an instance of the `Car` class shown in <<example-cascaded-validation-list>>, a |
| 555 |
`ConstraintViolation` will be created, if any of the `Person` objects contained in the passengers list |
| 556 |
has a `null` name. |
| 557 |
|
| 558 |
[[section-validating-bean-constraints]] |
| 559 |
=== Validating bean constraints |
| 560 |
|
| 561 |
The `Validator` interface is the most important object in Bean Validation. The next section shows how |
| 562 |
to obtain an `Validator` instance. Afterwards you'll learn how to use the different methods of the |
| 563 |
`Validator` interface. |
| 564 |
|
| 565 |
[[section-obtaining-validator]] |
| 566 |
==== Obtaining a `Validator` instance |
| 567 |
|
| 568 |
The first step towards validating an entity instance is to get hold of a `Validator` instance. The |
| 569 |
road to this instance leads via the `Validation` class and a `ValidatorFactory`. The easiest way is to |
| 570 |
use the static method `Validation#buildDefaultValidatorFactory()`: |
| 571 |
|
| 572 |
.`Validation#buildDefaultValidatorFactory()` |
| 573 |
==== |
| 574 |
[source, JAVA] |
| 575 |
---- |
| 576 |
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); |
| 577 |
Validator validator = factory.getValidator(); |
| 578 |
---- |
| 579 |
==== |
| 580 |
|
| 581 |
This bootstraps a validator in the default configuration. Refer to <<chapter-bootstrapping>> to |
| 582 |
learn more about the different bootstrapping methods and how to obtain a specifically configured |
| 583 |
`Validator` instance. |
| 584 |
|
| 585 |
==== Validator methods |
| 586 |
|
| 587 |
The `Validator` interface contains three methods that can be used to either validate entire entities |
| 588 |
or just single properties of the entity. |
| 589 |
|
| 590 |
All three methods return a `Set<ConstraintViolation>`. The set is empty, if the validation succeeds. |
| 591 |
Otherwise a `ConstraintViolation` instance is added for each violated constraint. |
| 592 |
|
| 593 |
All the validation methods have a var-args parameter which can be used to specify, which validation |
| 594 |
groups shall be considered when performing the validation. If the parameter is not specified the |
| 595 |
default validation group (`javax.validation.groups.Default`) is used. The topic of validation groups |
| 596 |
is discussed in detail in <<chapter-groups>>. |
| 597 |
|
| 598 |
===== `Validator#validate()` |
| 599 |
|
| 600 |
Use the `validate()` method to perform validation of all constraints of a given bean. |
| 601 |
<<example-validator-validate>> shows the validation of an instance of the `Car` class from |
| 602 |
<<example-property-level>> which fails to satisfy the `@NotNull` constraint on the `manufacturer` |
| 603 |
property. The validation call therefore returns one `ConstraintViolation` object. |
| 604 |
|
| 605 |
[[example-validator-validate]] |
| 606 |
.Using `Validator#validate()` |
| 607 |
==== |
| 608 |
[source, JAVA] |
| 609 |
---- |
| 610 |
Car car = new Car( null, true ); |
| 611 |
|
| 612 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); |
| 613 |
|
| 614 |
assertEquals( 1, constraintViolations.size() ); |
| 615 |
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() ); |
| 616 |
---- |
| 617 |
==== |
| 618 |
|
| 619 |
|
| 620 |
===== `Validator#validateProperty()` |
| 621 |
|
| 622 |
With help of the `validateProperty()` you can validate a single named property of a given object. The |
| 623 |
property name is the JavaBeans property name. |
| 624 |
|
| 625 |
.Using `Validator#validateProperty()` |
| 626 |
==== |
| 627 |
[source, JAVA] |
| 628 |
---- |
| 629 |
Car car = new Car( null, true ); |
| 630 |
|
| 631 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validateProperty( |
| 632 |
car, |
| 633 |
"manufacturer" |
| 634 |
); |
| 635 |
|
| 636 |
assertEquals( 1, constraintViolations.size() ); |
| 637 |
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() ); |
| 638 |
---- |
| 639 |
==== |
| 640 |
|
| 641 |
|
| 642 |
===== `Validator#validateValue()` |
| 643 |
|
| 644 |
By using the `validateValue()` method you can check whether a single property of a given class can be |
| 645 |
validated successfully, if the property had the specified value: |
| 646 |
|
| 647 |
.Using `Validator#validateValue()` |
| 648 |
==== |
| 649 |
[source, JAVA] |
| 650 |
---- |
| 651 |
Set<ConstraintViolation<Car>> constraintViolations = validator.validateValue( |
| 652 |
Car.class, |
| 653 |
"manufacturer", |
| 654 |
null |
| 655 |
); |
| 656 |
|
| 657 |
assertEquals( 1, constraintViolations.size() ); |
| 658 |
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() ); |
| 659 |
--- |
| 660 |
|
| 661 |
==== |
| 662 |
|
| 663 |
[NOTE] |
| 664 |
==== |
| 665 |
`@Valid` is not honored by `validateProperty()` or `validateValue()`. |
| 666 |
==== |
| 667 |
|
| 668 |
|
| 669 |
`Validator#validateProperty()` is for example used in the integration of Bean Validation into JSF 2 |
| 670 |
(see <<section-presentation-layer>>) to perform a validation of the values entered into a form |
| 671 |
before they are propagated to the model. |
| 672 |
|
| 673 |
[[section-constraint-violation-methods]] |
| 674 |
|
| 675 |
==== `ConstraintViolation` methods |
| 676 |
|
| 677 |
Now it is time to have a closer look at what a `ConstraintViolation` is. Using the different methods |
| 678 |
of `ConstraintViolation` a lot of useful information about the cause of the validation failure can be |
| 679 |
determined. <<table-constraint-violation>> gives an overview of these methods. The values in the |
| 680 |
"Example" column refer to <<example-validator-validate>>. |
| 681 |
|
| 682 |
[[table-constraint-violation]] |
| 683 |
.The various `ConstraintViolation` methods |
| 684 |
[options="header"] |
| 685 |
|=============== |
| 686 |
|Method|Usage|Example |
| 687 |
|`getMessage()`|The interpolated error message|"may not be null" |
| 688 |
|`getMessageTemplate()`|The non-interpolated error message|"{... NotNull.message}" |
| 689 |
|`getRootBean()`|The root bean being validated|car |
| 690 |
|`getRootBeanClass()`|The class of the root bean being validated|`Car.class` |
| 691 |
|`getLeafBean()`|If a bean constraint, the bean instance the constraint is |
| 692 |
applied on; If a property constraint, the bean instance hosting |
| 693 |
the property the constraint is applied on|`car` |
| 694 |
|`getPropertyPath()`|The property path to the validated value from root |
| 695 |
bean|contains one node with kind |
| 696 |
`PROPERTY` and name "manufacturer" |
| 697 |
|`getInvalidValue()`|The value failing to pass the constraint|`null` |
| 698 |
|`getConstraintDescriptor()`|Constraint metadata reported to fail|descriptor for `@NotNull` |
| 699 |
|
| 700 |
|=============== |
| 701 |
|
| 702 |
|
| 703 |
[[section-builtin-constraints]] |
| 704 |
=== Built-in constraints |
| 705 |
|
| 706 |
Hibernate Validator comprises a basic set of commonly used constraints. These are foremost the |
| 707 |
constraints defined by the Bean Validation specification (see <<table-spec-constraints>>). |
| 708 |
Additionally, Hibernate Validator provides useful custom constraints (see |
| 709 |
<<table-custom-constraints>> and <<table-custom-country-constraints>>). |
| 710 |
|
| 711 |
[[validator-defineconstraints-spec]] |
| 712 |
==== Bean Validation constraints |
| 713 |
|
| 714 |
<<table-spec-constraints>> shows purpose and supported data types of all constraints specified in |
| 715 |
the Bean Validation API. All these constraints apply to the field/property level, there are no |
| 716 |
class-level constraints defined in the Bean Validation specification. If you are using the Hibernate |
| 717 |
object-relational mapper, some of the constraints are taken into account when creating the DDL for |
| 718 |
your model (see column "Hibernate metadata impact"). |
| 719 |
|
| 720 |
|
| 721 |
[NOTE] |
| 722 |
==== |
| 723 |
Hibernate Validator allows some constraints to be applied to more data types than required by the |
| 724 |
Bean Validation specification (e.g. `@Max` can be applied to strings). Relying on this feature can |
| 725 |
impact portability of your application between Bean Validation providers. |
| 726 |
==== |
| 727 |
|
| 728 |
|
| 729 |
[[table-spec-constraints]] |
| 730 |
.Bean Validation constraints |
| 731 |
[options="header"] |
| 732 |
|=============== |
| 733 |
|Annotation|Supported data types|Use|Hibernate metadata impact |
| 734 |
|`@AssertFalse`|`Boolean`, |
| 735 |
`boolean`|Checks that the annotated element is |
| 736 |
false|None |
| 737 |
|`@AssertTrue`|`Boolean`, |
| 738 |
`boolean`|Checks that the annotated element is |
| 739 |
true|None |
| 740 |
|`@DecimalMax(value=,inclusive=)`|`BigDecimal`, |
| 741 |
`BigInteger`, |
| 742 |
`CharSequence`, |
| 743 |
`byte`, `short`, |
| 744 |
`int`, `long` and the |
| 745 |
respective wrappers of the primitive types; Additionally |
| 746 |
supported by HV: any sub-type of |
| 747 |
`Number`|Checks whether the annotated value is less than the |
| 748 |
specified maximum, when inclusive=false. |
| 749 |
Otherwise whether the value is less than or equal to the |
| 750 |
specified maximum. The parameter value is |
| 751 |
the string representation of the max value according to the |
| 752 |
`BigDecimal` string representation.|None |
| 753 |
|`@DecimalMin(value=,inclusive=)`|`BigDecimal`, |
| 754 |
`BigInteger`, |
| 755 |
`CharSequence`, |
| 756 |
`byte`, `short`, |
| 757 |
`int`, `long` and the |
| 758 |
respective wrappers of the primitive types; Additionally |
| 759 |
supported by HV: any sub-type of |
| 760 |
`Number`|Checks whether the annotated value is larger than the |
| 761 |
specified minimum, when inclusive=false. |
| 762 |
Otherwise whether the value is larger than or equal to the |
| 763 |
specified minimum. The parameter value is |
| 764 |
the string representation of the min value according to the |
| 765 |
`BigDecimal` string representation.|None |
| 766 |
|`@Digits(integer=,fraction=)`|BigDecimal, |
| 767 |
`BigInteger`, |
| 768 |
`CharSequence`, |
| 769 |
`byte`, `short`, |
| 770 |
`int`, `long` and the |
| 771 |
respective wrappers of the primitive types; Additionally |
| 772 |
supported by HV: any sub-type of |
| 773 |
`Number`|Checks whether the annotated value is a number having up to |
| 774 |
`integer` digits and |
| 775 |
`fraction` fractional digits|Defines column precision and scale |
| 776 |
|`@Future`|`java.util.Date`, |
| 777 |
`java.util.Calendar`, |
| 778 |
`java.time.chrono.ChronoZonedDateTime`, |
| 779 |
`java.time.Instant`, |
| 780 |
`java.time.OffsetDateTime`; Additionally |
| 781 |
supported by HV, if the link:$$http://joda-time.sourceforge.net/$$[Joda Time] |
| 782 |
date/time API is on the class path: any implementations of |
| 783 |
`ReadablePartial` and |
| 784 |
`ReadableInstant`|Checks whether the annotated date is in the |
| 785 |
future|None |
| 786 |
|`@Max(value=)`|`BigDecimal`, |
| 787 |
`BigInteger`, `byte`, |
| 788 |
`short`, `int`, |
| 789 |
`long` and the respective wrappers of the |
| 790 |
primitive types; Additionally supported by HV: any sub-type of |
| 791 |
`CharSequence` (the numeric value |
| 792 |
represented by the character sequence is evaluated), any |
| 793 |
sub-type of `Number`|Checks whether the annotated value is less than or equal |
| 794 |
to the specified maximum|Adds a check constraint on the column |
| 795 |
|`@Min(value=)`|`BigDecimal`, |
| 796 |
`BigInteger`, `byte`, |
| 797 |
`short`, `int`, |
| 798 |
`long` and the respective wrappers of the |
| 799 |
primitive types; Additionally supported by HV: any sub-type of |
| 800 |
`CharSequence` (the numeric value |
| 801 |
represented by the char sequence is evaluated), any sub-type of |
| 802 |
`Number`|Checks whether the annotated value is higher than or |
| 803 |
equal to the specified minimum|Adds a check constraint on the column |
| 804 |
|`@NotNull`|Any type|Checks that the annotated value is not |
| 805 |
`null`.|Column(s) are not nullable |
| 806 |
|`@Null`|Any type|Checks that the annotated value is |
| 807 |
`null`|None |
| 808 |
|`@Past`|`java.util.Date`, |
| 809 |
`java.util.Calendar`, |
| 810 |
`java.time.chrono.ChronoZonedDateTime`, |
| 811 |
`java.time.Instant`, |
| 812 |
`java.time.OffsetDateTime`; Additionally |
| 813 |
supported by HV, if the link:$$http://joda-time.sourceforge.net/$$[Joda Time] |
| 814 |
date/time API is on the class path: any implementations of |
| 815 |
`ReadablePartial` and |
| 816 |
`ReadableInstant`|Checks whether the annotated date is in the past|None |
| 817 |
|`@Pattern(regex=,flag=)`|`CharSequence`|Checks if the annotated string matches the regular |
| 818 |
expression `regex` considering the given |
| 819 |
flag `match`|None |
| 820 |
|`@Size(min=, max=)`|`CharSequence`, |
| 821 |
`Collection`, `Map` |
| 822 |
and arrays|Checks if the annotated element's size is between `min` and |
| 823 |
`max` (inclusive)|Column length will be set to |
| 824 |
`max` |
| 825 |
|`@Valid`|Any non-primitive type|Performs validation recursively on the associated object. |
| 826 |
If the object is a collection or an array, the elements are |
| 827 |
validated recursively. If the object is a map, the value |
| 828 |
elements are validated recursively.|None |
| 829 |
|
| 830 |
|=============== |
| 831 |
|
| 832 |
|
| 833 |
|
| 834 |
[NOTE] |
| 835 |
==== |
| 836 |
On top of the parameters indicated in <<table-spec-constraints>> each constraint has the parameters |
| 837 |
message, groups and payload. This is a requirement of the Bean Validation specification. |
| 838 |
==== |
| 839 |
|
| 840 |
|
| 841 |
[[validator-defineconstraints-hv-constraints]] |
| 842 |
==== Additional constraints |
| 843 |
|
| 844 |
In addition to the constraints defined by the Bean Validation API Hibernate Validator provides |
| 845 |
several useful custom constraints which are listed in <<table-custom-constraints>>. With one |
| 846 |
exception also these constraints apply to the field/property level, only `@ScriptAssert` is a class- |
| 847 |
level constraint. |
| 848 |
|
| 849 |
[[table-custom-constraints]] |
| 850 |
.Custom constraints |
| 851 |
[cols="4*", options="header"] |
| 852 |
|=============== |
| 853 |
|Annotation |
| 854 |
|Supported data types |
| 855 |
|Use |
| 856 |
|Hibernate metadata impact |
| 857 |
|
| 858 |
|`@CreditCardNumber(ignoreNonDigitCharacters=)` |
| 859 |
|`CharSequence` |
| 860 |
|Checks that the annotated character sequence passes the |
| 861 |
Luhn checksum test. Note, this validation aims to check for user |
| 862 |
mistakes, not credit card validity! See also |
| 863 |
http://www.merriampark.com/anatomycc.htm[Anatomy of Credit Card Numbers]. `ignoreNonDigitCharacters` |
| 864 |
allows to ignore non digit characters. The default is `false`. |
| 865 |
|None |
| 866 |
|
| 867 |
|`@EAN` |
| 868 |
|`CharSequence` |
| 869 |
|Checks that the annotated character sequence is a valid |
| 870 |
link:$$http://en.wikipedia.org/wiki/International_Article_Number_%28EAN%29$$[EAN] barcode. |
| 871 |
type determines the type of barcode. The default is EAN-13. |
| 872 |
|None |
| 873 |
|
| 874 |
|`@Email` |
| 875 |
|`CharSequence` |
| 876 |
|Checks whether the specified character sequence is a valid email address. The optional parameters |
| 877 |
`regexp` and `flags` allow to specify an additional regular expression (including regular expression |
| 878 |
flags) which the email must match. |
| 879 |
|None |
| 880 |
|
| 881 |
|`@Length(min=, + |
| 882 |
max=)` |
| 883 |
|`CharSequence` |
| 884 |
|Validates that the annotated character sequence is |
| 885 |
between `min` and |
| 886 |
`max` included |
| 887 |
|Column length will be set to max |
| 888 |
|
| 889 |
|`@LuhnCheck(startIndex= , + |
| 890 |
endIndex=, + |
| 891 |
checkDigitIndex=, + |
| 892 |
ignoreNonDigitCharacters=)` |
| 893 |
|`CharSequence` |
| 894 |
|Checks that the digits within the annotated character |
| 895 |
sequence pass the Luhn checksum algorithm (see also |
| 896 |
link:$$http://en.wikipedia.org/wiki/Luhn_algorithm$$[Luhn algorithm]). `startIndex` and |
| 897 |
`endIndex` allow to only run the algorithm on |
| 898 |
the specified sub-string. `checkDigitIndex` |
| 899 |
allows to use an arbitrary digit within the character sequence |
| 900 |
as the check digit. If not specified it is assumed that the |
| 901 |
check digit is part of the specified range. Last but not least, |
| 902 |
`ignoreNonDigitCharacters` allows to ignore |
| 903 |
non digit characters. |
| 904 |
|None |
| 905 |
|
| 906 |
|`@Mod10Check(multiplier=, + |
| 907 |
weight=, + |
| 908 |
startIndex=, + |
| 909 |
endIndex=, + |
| 910 |
checkDigitIndex=, + |
| 911 |
ignoreNonDigitCharacters=)` |
| 912 |
|`CharSequence` |
| 913 |
|Checks that the digits within the annotated character |
| 914 |
sequence pass the generic mod 10 checksum algorithm. |
| 915 |
`multiplier` determines the multiplier for |
| 916 |
odd numbers (defaults to 3), `weight` the |
| 917 |
weight for even numbers (defaults to 1). |
| 918 |
`startIndex` and |
| 919 |
`endIndex` allow to only run the algorithm on |
| 920 |
the specified sub-string. `checkDigitIndex` |
| 921 |
allows to use an arbitrary digit within the character sequence |
| 922 |
as the check digit. If not specified it is assumed that the |
| 923 |
check digit is part of the specified range. Last but not least, |
| 924 |
`ignoreNonDigitCharacters` allows to ignore |
| 925 |
non digit characters. |
| 926 |
|None |
| 927 |
|
| 928 |
|`@Mod11Check(threshold=, + |
| 929 |
startIndex=, + |
| 930 |
endIndex=, + |
| 931 |
checkDigitIndex=, + |
| 932 |
ignoreNonDigitCharacters=, + |
| 933 |
treatCheck10As=, + |
| 934 |
treatCheck11As=)` |
| 935 |
|`CharSequence` |
| 936 |
|Checks that the digits within the annotated character |
| 937 |
sequence pass the mod 11 checksum algorithm. |
| 938 |
`threshold` specifies the threshold for the |
| 939 |
mod11 multiplier growth; if no value is specified the multiplier |
| 940 |
will grow indefinitely. `treatCheck10As` |
| 941 |
and `treatCheck11As` specify the check |
| 942 |
digits to be used when the mod 11 checksum equals 10 or 11, |
| 943 |
respectively. Default to X and 0, respectively. |
| 944 |
`startIndex`, `endIndex` |
| 945 |
`checkDigitIndex` and |
| 946 |
`ignoreNonDigitCharacters` carry the same |
| 947 |
semantics as in `@Mod10Check`. |
| 948 |
|None |
| 949 |
|
| 950 |
|`@NotBlank` |
| 951 |
|`CharSequence` |
| 952 |
|Checks that the annotated character sequence is not null |
| 953 |
and the trimmed length is greater than 0. The difference to |
| 954 |
`@NotEmpty` is that this constraint can |
| 955 |
only be applied on strings and that trailing white-spaces are |
| 956 |
ignored. |
| 957 |
|None |
| 958 |
|
| 959 |
|`@NotEmpty` |
| 960 |
|`CharSequence`, `Collection`, `Map` and arrays |
| 961 |
|Checks whether the annotated element is not null nor empty |
| 962 |
|None |
| 963 |
|
| 964 |
|`@Range(min=, + |
| 965 |
max=)` |
| 966 |
|`BigDecimal`, `BigInteger`, `CharSequence`, `byte`, `short`, `int`, `long` and the respective wrappers of the |
| 967 |
primitive types |
| 968 |
|Checks whether the annotated value lies between (inclusive) the specified minimum and maximum |
| 969 |
|None |
| 970 |
|
| 971 |
|`@SafeHtml(whitelistType= , + |
| 972 |
additionalTags=, + |
| 973 |
additionalTagsWithAttributes=)` |
| 974 |
|`CharSequence` |
| 975 |
|Checks whether the annotated value |
| 976 |
contains potentially malicious fragments such as `<script/>`. In order to use this |
| 977 |
constraint, the |
| 978 |
link:$$http://jsoup.org/$$[jsoup] library must be part of the class path. |
| 979 |
With the `whitelistType` attribute a predefined whitelist type can be chosen which can |
| 980 |
be refined via `additionalTags` or `additionalTagsWithAttributes`. The former allows to |
| 981 |
add tags without any attributes, whereas the latter allows to specify tags and |
| 982 |
optionally allowed attributes using the annotation `@SafeHtml.Tag`. |
| 983 |
|None |
| 984 |
|
| 985 |
|`@ScriptAssert(lang=, + |
| 986 |
script=, + |
| 987 |
alias=)` |
| 988 |
|Any type |
| 989 |
|Checks whether the given script can successfully be |
| 990 |
evaluated against the annotated element. In order to use this |
| 991 |
constraint, an implementation of the Java Scripting API as |
| 992 |
defined by JSR 223 ("Scripting for the |
| 993 |
Java^TM^ Platform") must part of the |
| 994 |
class path. The expressions to be evaluated can be written in |
| 995 |
any scripting or expression language, for which a JSR 223 |
| 996 |
compatible engine can be found in the class path. |
| 997 |
|None |
| 998 |
|
| 999 |
|`@URL(protocol=, + |
| 1000 |
host=, + |
| 1001 |
port=, + |
| 1002 |
regexp=, + |
| 1003 |
flags=)` |
| 1004 |
|`CharSequence` |
| 1005 |
|Checks if the annotated character sequence is a valid URL |
| 1006 |
according to RFC2396. If any of the optional parameters |
| 1007 |
`protocol`, `host` or |
| 1008 |
`port` are specified, the corresponding URL |
| 1009 |
fragments must match the specified values. The optional |
| 1010 |
parameters `regexp` and |
| 1011 |
`flags` allow to specify an additional |
| 1012 |
regular expression (including regular expression flags) which |
| 1013 |
the URL must match. Per default this constraint used the `java.net.URL` constructor to |
| 1014 |
verify whether a given string represents a valid URL. A regular expression based version is also |
| 1015 |
available - `RegexpURLValidator` - which can be configured via XML |
| 1016 |
(see <<section-mapping-xml-constraints>>) or the programmatic API |
| 1017 |
(see <<section-programmatic-constraint-definition>>). |
| 1018 |
|None |
| 1019 |
|
| 1020 |
|=============== |
| 1021 |
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
===== Country specific constraints |
| 1026 |
|
| 1027 |
Hibernate Validator offers also some country specific constraints, e.g. for the validation of social |
| 1028 |
security numbers. |
| 1029 |
|
| 1030 |
[NOTE] |
| 1031 |
==== |
| 1032 |
If you have to implement a country specific constraint, consider making it a contribution to |
| 1033 |
Hibernate Validator! |
| 1034 |
==== |
| 1035 |
|
| 1036 |
|
| 1037 |
[[table-custom-country-constraints]] |
| 1038 |
.Custom country specific constraints |
| 1039 |
[options="header"] |
| 1040 |
|=============== |
| 1041 |
|Annotation|Supported data types|Use|Country|Hibernate metadata impact |
| 1042 |
|`@CNPJ`|`CharSequence`|Checks that the annotated character sequence represents |
| 1043 |
a Brazilian corporate tax payer registry number (Cadastro de |
| 1044 |
Pessoa Juríeddica)|Brazil|None |
| 1045 |
|`@CPF`|`CharSequence`|Checks that the annotated character sequence represents |
| 1046 |
a Brazilian individual taxpayer registry number (Cadastro de |
| 1047 |
Pessoa Fídsica)|Brazil|None |
| 1048 |
|`@TituloEleitoral`|`CharSequence`|Checks that the annotated character sequence represents |
| 1049 |
a Brazilian voter ID card number (link:$$http://ghiorzi.org/cgcancpf.htm$$[Título Eleitoral])|Brazil|None |
| 1050 |
|
| 1051 |
|=============== |
| 1052 |
|
| 1053 |
|
| 1054 |
|
| 1055 |
[TIP] |
| 1056 |
==== |
| 1057 |
In some cases neither the Bean Validation constraints nor the custom constraints provided by |
| 1058 |
Hibernate Validator will fulfill your requirements. In this case you can easily write your own |
| 1059 |
constraint. You can find more information in <<validator-customconstraints>>. |
| 1060 |
==== |
| 1061 |
|
| 1062 |
|