| 1 |
[[validator-customconstraints]] |
| 2 |
== Creating custom constraints |
| 3 |
|
| 4 |
The Bean Validation API defines a whole set of standard constraint annotations such as `@NotNull`, |
| 5 |
`@Size` etc. In cases where these buit-in constraints are not sufficient, you cean easily create |
| 6 |
custom constraints tailored to your specific validation requirements. |
| 7 |
|
| 8 |
[[validator-customconstraints-simple]] |
| 9 |
=== Creating a simple constraint |
| 10 |
|
| 11 |
To create a custom constraint, the following three steps are required: |
| 12 |
|
| 13 |
* Create a constraint annotation |
| 14 |
* Implement a validator |
| 15 |
* Define a default error message |
| 16 |
|
| 17 |
[[validator-customconstraints-constraintannotation]] |
| 18 |
==== The constraint annotation |
| 19 |
|
| 20 |
This section shows how to write a constraint annotation which can be used to ensure that a given |
| 21 |
string is either completely upper case or lower case. Later on this constraint will be applied to |
| 22 |
the `licensePlate` field of the `Car` class from <<validator-gettingstarted>> to ensure, that |
| 23 |
the field is always an upper-case string. |
| 24 |
|
| 25 |
The first thing needed is a way to express the two case modes. While you could use `String` constants, |
| 26 |
a better approach is using a Java 5 enum for that purpose: |
| 27 |
|
| 28 |
.Enum `CaseMode` to express upper vs. lower case |
| 29 |
==== |
| 30 |
[source, JAVA] |
| 31 |
---- |
| 32 |
package org.hibernate.validator.referenceguide.chapter06; |
| 33 |
|
| 34 |
public enum CaseMode { |
| 35 |
UPPER, |
| 36 |
LOWER; |
| 37 |
} |
| 38 |
---- |
| 39 |
==== |
| 40 |
|
| 41 |
The next step is to define the actual constraint annotation. If you've never designed an annotation |
| 42 |
before, this may look a bit scary, but actually it's not that hard: |
| 43 |
|
| 44 |
[[example-defining-custom-constraint]] |
| 45 |
.Defining the `@CheckCase` constraint annotation |
| 46 |
==== |
| 47 |
[source, JAVA] |
| 48 |
---- |
| 49 |
package org.hibernate.validator.referenceguide.chapter06; |
| 50 |
|
| 51 |
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) |
| 52 |
@Retention(RUNTIME) |
| 53 |
@Constraint(validatedBy = CheckCaseValidator.class) |
| 54 |
@Documented |
| 55 |
public @interface CheckCase { |
| 56 |
|
| 57 |
String message() default "{org.hibernate.validator.referenceguide.chapter06.CheckCase." + |
| 58 |
"message}"; |
| 59 |
|
| 60 |
Class<?>[] groups() default { }; |
| 61 |
|
| 62 |
Class<? extends Payload>[] payload() default { }; |
| 63 |
|
| 64 |
CaseMode value(); |
| 65 |
|
| 66 |
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) |
| 67 |
@Retention(RUNTIME) |
| 68 |
@Documented |
| 69 |
@interface List { |
| 70 |
CheckCase[] value(); |
| 71 |
} |
| 72 |
} |
| 73 |
---- |
| 74 |
==== |
| 75 |
|
| 76 |
An annotation type is defined using the `@interface` keyword. All attributes of an annotation type are |
| 77 |
declared in a method-like manner. The specification of the Bean Validation API demands, that any |
| 78 |
constraint annotation defines |
| 79 |
|
| 80 |
* an attribute `message` that returns the default key for creating error messages in case the |
| 81 |
constraint is violated |
| 82 |
|
| 83 |
* an attribute `groups` that allows the specification of validation groups, to which this constraint |
| 84 |
belongs (see <<chapter-groups>>). This must default to an empty array of type Class<?>. |
| 85 |
|
| 86 |
* an attribute `payload` that can be used by clients of the Bean Validation API to assign custom |
| 87 |
payload objects to a constraint. This attribute is not used by the API itself. An example for a |
| 88 |
custom payload could be the definition of a severity: |
| 89 |
+ |
| 90 |
==== |
| 91 |
[source, JAVA] |
| 92 |
---- |
| 93 |
public class Severity { |
| 94 |
public interface Info extends Payload { |
| 95 |
} |
| 96 |
|
| 97 |
public interface Error extends Payload { |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
public class ContactDetails { |
| 102 |
@NotNull(message = "Name is mandatory", payload = Severity.Error.class) |
| 103 |
private String name; |
| 104 |
|
| 105 |
@NotNull(message = "Phone number not specified, but not mandatory", |
| 106 |
payload = Severity.Info.class) |
| 107 |
private String phoneNumber; |
| 108 |
|
| 109 |
// ... |
| 110 |
} |
| 111 |
---- |
| 112 |
==== |
| 113 |
+ |
| 114 |
Now a client can after the validation of a `ContactDetails` instance access the severity of a |
| 115 |
constraint using `ConstraintViolation.getConstraintDescriptor().getPayload()` and adjust its behavior |
| 116 |
depending on the severity. |
| 117 |
|
| 118 |
Besides these three mandatory attributes there is another one, `value`, allowing for the required case |
| 119 |
mode to be specified. The name `value` is a special one, which can be omitted when using the |
| 120 |
annotation, if it is the only attribute specified, as e.g. in `@CheckCase(CaseMode.UPPER)`. |
| 121 |
|
| 122 |
In addition, the constraint annotation is decorated with a couple of meta annotations: |
| 123 |
|
| 124 |
* `@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})`: Defines the supported target element types |
| 125 |
for the constraint. `@CheckCase` may be used on fields (element type `FIELD`), JavaBeans properties as |
| 126 |
well as method return values (`METHOD`) and method/constructor parameters (`PARAMETER`). The element |
| 127 |
type `ANNOTATION_TYPE` allows for the creation of composed constraints |
| 128 |
(see <<section-constraint-composition>>) based on `@CheckCase`. |
| 129 |
+ |
| 130 |
When creating a class-level constraint (see <<validator-usingvalidator-classlevel>>), the element |
| 131 |
type `TYPE` would have to be used. Constraints targeting the return value of a constructor need to |
| 132 |
support the element type `CONSTRUCTOR`. Cross-parameter constraints (see |
| 133 |
<<section-cross-parameter-constraints>>) which are used to validate all the parameters of a method |
| 134 |
or constructor together, must support `METHOD` or `CONSTRUCTOR`, respectively. |
| 135 |
|
| 136 |
* `@Retention(RUNTIME)`: Specifies, that annotations of this type will be available at runtime by the |
| 137 |
means of reflection |
| 138 |
|
| 139 |
* `@Constraint(validatedBy = CheckCaseValidator.class)`: Marks the annotation type as constraint |
| 140 |
annotation and specifies the validator to be used to validate elements annotated with `@CheckCase`. |
| 141 |
If a constraint may be used on several data types, several validators may be specified, one for |
| 142 |
each data type. |
| 143 |
|
| 144 |
* `@Documented`: Says, that the use of `@CheckCase` will be contained in the JavaDoc of elements |
| 145 |
annotated with it |
| 146 |
|
| 147 |
Finally, there is an inner annotation type named `List`. This annotation allows to specify several |
| 148 |
`@CheckCase` annotations on the same element, e.g. with different validation groups and messages. |
| 149 |
While also another name could be used, the Bean Validation specification recommends to use the name |
| 150 |
`List` and make the annotation an inner annotation of the corresponding constraint type. |
| 151 |
|
| 152 |
[[section-constraint-validator]] |
| 153 |
==== The constraint validator |
| 154 |
|
| 155 |
Having defined the annotation, you need to create a constraint validator, which is able to validate |
| 156 |
elements with a `@CheckCase` annotation. To do so, implement the interface `ConstraintValidator` as |
| 157 |
shown below: |
| 158 |
|
| 159 |
[[example-constraint-validator]] |
| 160 |
.Implementing a constraint validator for the constraint `@CheckCase` |
| 161 |
==== |
| 162 |
[source, JAVA] |
| 163 |
---- |
| 164 |
package org.hibernate.validator.referenceguide.chapter06; |
| 165 |
|
| 166 |
public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> { |
| 167 |
|
| 168 |
private CaseMode caseMode; |
| 169 |
|
| 170 |
@Override |
| 171 |
public void initialize(CheckCase constraintAnnotation) { |
| 172 |
this.caseMode = constraintAnnotation.value(); |
| 173 |
} |
| 174 |
|
| 175 |
@Override |
| 176 |
public boolean isValid(String object, ConstraintValidatorContext constraintContext) { |
| 177 |
if ( object == null ) { |
| 178 |
return true; |
| 179 |
} |
| 180 |
|
| 181 |
if ( caseMode == CaseMode.UPPER ) { |
| 182 |
return object.equals( object.toUpperCase() ); |
| 183 |
} |
| 184 |
else { |
| 185 |
return object.equals( object.toLowerCase() ); |
| 186 |
} |
| 187 |
} |
| 188 |
} |
| 189 |
---- |
| 190 |
==== |
| 191 |
|
| 192 |
The `ConstraintValidator` interface defines two type parameters which are set in the implementation. |
| 193 |
The first one specifies the annotation type to be validated (`CheckCase`), the second one the type of |
| 194 |
elements, which the validator can handle (`String`). In case a constraint supports several data types, |
| 195 |
a `ConstraintValidator` for each allowed type has to be implemented and registered at the constraint |
| 196 |
annotation as shown above. |
| 197 |
|
| 198 |
The implementation of the validator is straightforward. The `initialize()` method gives you access to |
| 199 |
the attribute values of the validated constraint and allows you to store them in a field of the |
| 200 |
validator as shown in the example. |
| 201 |
|
| 202 |
The `isValid()` method contains the actual validation logic. For `@CheckCase` this is the check whether |
| 203 |
a given string is either completely lower case or upper case, depending on the case mode retrieved |
| 204 |
in `initialize()`. Note that the Bean Validation specification recommends to consider null values as |
| 205 |
being valid. If `null` is not a valid value for an element, it should be annotated with `@NotNull` |
| 206 |
explicitly. |
| 207 |
|
| 208 |
===== The `ConstraintValidatorContext` |
| 209 |
|
| 210 |
<<example-constraint-validator>> |
| 211 |
relies on the default error message generation by just returning `true` or `false` from the `isValid()` |
| 212 |
method. Using the passed `ConstraintValidatorContext` object it is possible to either add additional |
| 213 |
error messages or completely disable the default error message generation and solely define custom |
| 214 |
error messages. The `ConstraintValidatorContext` API is modeled as fluent interface and is best |
| 215 |
demonstrated with an example: |
| 216 |
|
| 217 |
[[example-constraint-validator-context]] |
| 218 |
.Using `ConstraintValidatorContext` to define custom error messages |
| 219 |
==== |
| 220 |
[source, JAVA] |
| 221 |
---- |
| 222 |
package org.hibernate.validator.referenceguide.chapter06.constraintvalidatorcontext; |
| 223 |
|
| 224 |
public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> { |
| 225 |
|
| 226 |
private CaseMode caseMode; |
| 227 |
|
| 228 |
@Override |
| 229 |
public void initialize(CheckCase constraintAnnotation) { |
| 230 |
this.caseMode = constraintAnnotation.value(); |
| 231 |
} |
| 232 |
|
| 233 |
@Override |
| 234 |
public boolean isValid(String object, ConstraintValidatorContext constraintContext) { |
| 235 |
if ( object == null ) { |
| 236 |
return true; |
| 237 |
} |
| 238 |
|
| 239 |
boolean isValid; |
| 240 |
if ( caseMode == CaseMode.UPPER ) { |
| 241 |
isValid = object.equals( object.toUpperCase() ); |
| 242 |
} |
| 243 |
else { |
| 244 |
isValid = object.equals( object.toLowerCase() ); |
| 245 |
} |
| 246 |
|
| 247 |
if ( !isValid ) { |
| 248 |
constraintContext.disableDefaultConstraintViolation(); |
| 249 |
constraintContext.buildConstraintViolationWithTemplate( |
| 250 |
"{org.hibernate.validator.referenceguide.chapter03." + |
| 251 |
"constraintvalidatorcontext.CheckCase.message}" |
| 252 |
) |
| 253 |
.addConstraintViolation(); |
| 254 |
} |
| 255 |
|
| 256 |
return isValid; |
| 257 |
} |
| 258 |
} |
| 259 |
---- |
| 260 |
==== |
| 261 |
|
| 262 |
<<example-constraint-validator-context>> |
| 263 |
shows how you can disable the default error message generation and add a custom error message using |
| 264 |
a specified message template. In this example the use of the `ConstraintValidatorContext` results in |
| 265 |
the same error message as the default error message generation. |
| 266 |
|
| 267 |
[TIP] |
| 268 |
==== |
| 269 |
It is important to add each configured constraint violation by calling `addConstraintViolation()`. |
| 270 |
Only after that the new constraint violation will be created. |
| 271 |
==== |
| 272 |
|
| 273 |
Refer to <<section-custom-property-paths>> to learn how to use the `ConstraintValidatorContext` API to |
| 274 |
control the property path of constraint violations for class-level constraints. |
| 275 |
|
| 276 |
[[validator-customconstraints-errormessage]] |
| 277 |
==== The error message |
| 278 |
|
| 279 |
The last missing building block is an error message which should be used in case a `@CheckCase` |
| 280 |
constraint is violated. To define this, create a file _ValidationMessages.properties_ with the |
| 281 |
following contents (see also <<section-message-interpolation>>): |
| 282 |
|
| 283 |
.Defining a custom error message for the `CheckCase` constraint |
| 284 |
==== |
| 285 |
---- |
| 286 |
org.hibernate.validator.referenceguide.chapter06.CheckCase.message=Case mode must be {value}. |
| 287 |
---- |
| 288 |
==== |
| 289 |
|
| 290 |
If a validation error occurs, the validation runtime will use the default value, that you specified |
| 291 |
for the message attribute of the `@CheckCase` annotation to look up the error message in this resource |
| 292 |
bundle. |
| 293 |
|
| 294 |
[[validator-customconstraints-using]] |
| 295 |
==== Using the constraint |
| 296 |
|
| 297 |
You can now use the constraint in the `Car` class from the <<validator-gettingstarted>> chapter to |
| 298 |
specify that the `licensePlate` field should only contain upper-case strings: |
| 299 |
|
| 300 |
[[example-car-with-checkcase]] |
| 301 |
.Applying the `@CheckCase` constraint |
| 302 |
==== |
| 303 |
[source, JAVA] |
| 304 |
---- |
| 305 |
package org.hibernate.validator.referenceguide.chapter06; |
| 306 |
|
| 307 |
public class Car { |
| 308 |
|
| 309 |
@NotNull |
| 310 |
private String manufacturer; |
| 311 |
|
| 312 |
@NotNull |
| 313 |
@Size(min = 2, max = 14) |
| 314 |
@CheckCase(CaseMode.UPPER) |
| 315 |
private String licensePlate; |
| 316 |
|
| 317 |
@Min(2) |
| 318 |
private int seatCount; |
| 319 |
|
| 320 |
public Car ( String manufacturer, String licencePlate, int seatCount ) { |
| 321 |
this.manufacturer = manufacturer; |
| 322 |
this.licensePlate = licencePlate; |
| 323 |
this.seatCount = seatCount; |
| 324 |
} |
| 325 |
|
| 326 |
//getters and setters ... |
| 327 |
} |
| 328 |
---- |
| 329 |
==== |
| 330 |
|
| 331 |
Finally, <<example-using-checkcase>> demonstrates how validating a `Car` instance with an invalid |
| 332 |
license plate causes the `@CheckCase` constraint to be violated. |
| 333 |
|
| 334 |
[[example-using-checkcase]] |
| 335 |
.Validating objects with the `@CheckCase` constraint |
| 336 |
==== |
| 337 |
[source, JAVA] |
| 338 |
---- |
| 339 |
//invalid license plate |
| 340 |
Car car = new Car( "Morris", "dd-ab-123", 4 ); |
| 341 |
Set<ConstraintViolation<Car>> constraintViolations = |
| 342 |
validator.validate( car ); |
| 343 |
assertEquals( 1, constraintViolations.size() ); |
| 344 |
assertEquals( |
| 345 |
"Case mode must be UPPER.", |
| 346 |
constraintViolations.iterator().next().getMessage() |
| 347 |
); |
| 348 |
|
| 349 |
//valid license plate |
| 350 |
car = new Car( "Morris", "DD-AB-123", 4 ); |
| 351 |
|
| 352 |
constraintViolations = validator.validate( car ); |
| 353 |
|
| 354 |
assertEquals( 0, constraintViolations.size() ); |
| 355 |
---- |
| 356 |
==== |
| 357 |
|
| 358 |
[[section-class-level-constraints]] |
| 359 |
=== Class-level constraints |
| 360 |
|
| 361 |
As discussed earlier, constraints can also be applied on the class level to validate the state of an |
| 362 |
entire object. Class-level constraints are defined in the same was as are property constraints. |
| 363 |
<<example-implementing-classlevel-constraint>> shows constraint annotation and validator of the |
| 364 |
`@ValidPassengerCount` constraint you already saw in use in <<example-class-level>>. |
| 365 |
|
| 366 |
[[example-implementing-classlevel-constraint]] |
| 367 |
.Implementing a class-level constraint |
| 368 |
==== |
| 369 |
[source, JAVA] |
| 370 |
---- |
| 371 |
package org.hibernate.validator.referenceguide.chapter06.classlevel; |
| 372 |
|
| 373 |
@Target({ TYPE, ANNOTATION_TYPE }) |
| 374 |
@Retention(RUNTIME) |
| 375 |
@Constraint(validatedBy = { ValidPassengerCountValidator.class }) |
| 376 |
@Documented |
| 377 |
public @interface ValidPassengerCount { |
| 378 |
|
| 379 |
String message() default "{org.hibernate.validator.referenceguide.chapter06.classlevel." + |
| 380 |
"ValidPassengerCount.message}"; |
| 381 |
|
| 382 |
Class<?>[] groups() default { }; |
| 383 |
|
| 384 |
Class<? extends Payload>[] payload() default { }; |
| 385 |
} |
| 386 |
---- |
| 387 |
|
| 388 |
[source, JAVA] |
| 389 |
---- |
| 390 |
package org.hibernate.validator.referenceguide.chapter06.classlevel; |
| 391 |
|
| 392 |
public class ValidPassengerCountValidator |
| 393 |
implements ConstraintValidator<ValidPassengerCount, Car> { |
| 394 |
|
| 395 |
@Override |
| 396 |
public void initialize(ValidPassengerCount constraintAnnotation) { |
| 397 |
} |
| 398 |
|
| 399 |
@Override |
| 400 |
public boolean isValid(Car car, ConstraintValidatorContext context) { |
| 401 |
if ( car == null ) { |
| 402 |
return true; |
| 403 |
} |
| 404 |
|
| 405 |
return car.getPassengers().size() <= car.getSeatCount(); |
| 406 |
} |
| 407 |
} |
| 408 |
---- |
| 409 |
==== |
| 410 |
|
| 411 |
As the example demonstrates, you need to use the element type `TYPE` in the `@Target` annotation. This |
| 412 |
allows the constraint to be put on type definitions. The validator of the constraint in the example |
| 413 |
receives a `Car` in the `isValid()` method and can access the complete object state to decide whether |
| 414 |
the given instance is valid or not. |
| 415 |
|
| 416 |
[[section-custom-property-paths]] |
| 417 |
==== Custom property paths |
| 418 |
|
| 419 |
By default the constraint violation for a class-level constraint is reported on the level of the |
| 420 |
annotated type, e.g. `Car`. |
| 421 |
|
| 422 |
In some cases it is preferable though that the violation's property path refers to one of the |
| 423 |
involved properties. For instance you might want to report the `@ValidPassengerCount` constraint |
| 424 |
against the passengers property instead of the `Car` bean. |
| 425 |
|
| 426 |
<<example-custom-error>> |
| 427 |
shows how this can be done by using the constraint validator context passed to `isValid()` to build a |
| 428 |
custom constraint violation with a property node for the property passengers. Note that you also |
| 429 |
could add several property nodes, pointing to a sub-entity of the validated bean. |
| 430 |
|
| 431 |
[[example-custom-error]] |
| 432 |
.Adding a new `ConstraintViolation` with custom property path |
| 433 |
==== |
| 434 |
[source, JAVA] |
| 435 |
---- |
| 436 |
package org.hibernate.validator.referenceguide.chapter06.custompath; |
| 437 |
|
| 438 |
public class ValidPassengerCountValidator |
| 439 |
implements ConstraintValidator<ValidPassengerCount, Car> { |
| 440 |
|
| 441 |
@Override |
| 442 |
public void initialize(ValidPassengerCount constraintAnnotation) { |
| 443 |
} |
| 444 |
|
| 445 |
@Override |
| 446 |
public boolean isValid(Car car, ConstraintValidatorContext constraintValidatorContext) { |
| 447 |
if ( car == null ) { |
| 448 |
return true; |
| 449 |
} |
| 450 |
|
| 451 |
boolean isValid = car.getPassengers().size() <= car.getSeatCount(); |
| 452 |
|
| 453 |
if ( !isValid ) { |
| 454 |
constraintValidatorContext.disableDefaultConstraintViolation(); |
| 455 |
constraintValidatorContext |
| 456 |
.buildConstraintViolationWithTemplate( "{my.custom.template}" ) |
| 457 |
.addPropertyNode( "passengers" ).addConstraintViolation(); |
| 458 |
} |
| 459 |
|
| 460 |
return isValid; |
| 461 |
} |
| 462 |
} |
| 463 |
---- |
| 464 |
==== |
| 465 |
|
| 466 |
[[section-cross-parameter-constraints]] |
| 467 |
=== Cross-parameter constraints |
| 468 |
|
| 469 |
Bean Validation distinguishes between two different kinds of constraints. |
| 470 |
|
| 471 |
Generic constraints (which have been discussed so far) apply to the annotated element, e.g. a type, |
| 472 |
field, method parameter or return value etc. Cross-parameter constraints, in contrast, apply to the |
| 473 |
array of parameters of a method or constructor and can be used to express validation logic which |
| 474 |
depends on several parameter values. |
| 475 |
|
| 476 |
In order to define a cross-parameter constraint, its validator class must be annotated with |
| 477 |
`@SupportedValidationTarget(ValidationTarget.PARAMETERS)`. The type parameter `T` from the |
| 478 |
`ConstraintValidator` interface must resolve to either `Object` or `Object[]` in order to receive the |
| 479 |
array of method/constructor arguments in the `isValid()` method. |
| 480 |
|
| 481 |
The following example shows the definition of a cross-parameter constraint which can be used to |
| 482 |
check that two `Date` parameters of a method are in the correct order: |
| 483 |
|
| 484 |
.Cross-parameter constraint |
| 485 |
==== |
| 486 |
[source, JAVA] |
| 487 |
---- |
| 488 |
package org.hibernate.validator.referenceguide.chapter06.crossparameter; |
| 489 |
|
| 490 |
@Constraint(validatedBy = ConsistentDateParameterValidator.class) |
| 491 |
@Target({ METHOD, CONSTRUCTOR, ANNOTATION_TYPE }) |
| 492 |
@Retention(RUNTIME) |
| 493 |
@Documented |
| 494 |
public @interface ConsistentDateParameters { |
| 495 |
|
| 496 |
String message() default "{org.hibernate.validator.referenceguide.chapter06." + |
| 497 |
"crossparameter.ConsistentDateParameters.message}"; |
| 498 |
|
| 499 |
Class<?>[] groups() default { }; |
| 500 |
|
| 501 |
Class<? extends Payload>[] payload() default { }; |
| 502 |
} |
| 503 |
---- |
| 504 |
==== |
| 505 |
|
| 506 |
The definition of a cross-parameter constraint isn't any different from defining a generic |
| 507 |
constraint, i.e. it must specify the members `message()`, `groups()` and `payload()` and be annotated with |
| 508 |
`@Constraint`. This meta annotation also specifies the corresponding validator, which is shown in |
| 509 |
<<example-cross-parameter-validator>>. Note that besides the element types `METHOD` and `CONSTRUCTOR` |
| 510 |
also `ANNOTATION_TYPE` is specified as target of the annotation, in order to enable the creation of |
| 511 |
composed constraints based on `@ConsistentDateParameters` (see |
| 512 |
<<section-constraint-composition>>). |
| 513 |
|
| 514 |
[NOTE] |
| 515 |
==== |
| 516 |
Cross-parameter constraints are specified directly on the declaration of a method or constructor, |
| 517 |
which is also the case for return value constraints. In order to improve code readability, it is |
| 518 |
therefore recommended to chose constraint names - such as `@ConsistentDateParameters` - which make the |
| 519 |
constraint target apparent. |
| 520 |
==== |
| 521 |
|
| 522 |
[[example-cross-parameter-validator]] |
| 523 |
.Generic and cross-parameter constraint |
| 524 |
==== |
| 525 |
[source, JAVA] |
| 526 |
---- |
| 527 |
package org.hibernate.validator.referenceguide.chapter06.crossparameter; |
| 528 |
|
| 529 |
@SupportedValidationTarget(ValidationTarget.PARAMETERS) |
| 530 |
public class ConsistentDateParameterValidator implements |
| 531 |
ConstraintValidator<ConsistentDateParameters, Object[]> { |
| 532 |
|
| 533 |
@Override |
| 534 |
public void initialize(ConsistentDateParameters constraintAnnotation) { |
| 535 |
} |
| 536 |
|
| 537 |
@Override |
| 538 |
public boolean isValid(Object[] value, ConstraintValidatorContext context) { |
| 539 |
if ( value.length != 2 ) { |
| 540 |
throw new IllegalArgumentException( "Illegal method signature" ); |
| 541 |
} |
| 542 |
|
| 543 |
//leave null-checking to @NotNull on individual parameters |
| 544 |
if ( value[0] == null || value[1] == null ) { |
| 545 |
return true; |
| 546 |
} |
| 547 |
|
| 548 |
if ( !( value[0] instanceof Date ) || !( value[1] instanceof Date ) ) { |
| 549 |
throw new IllegalArgumentException( |
| 550 |
"Illegal method signature, expected two " + |
| 551 |
"parameters of type Date." |
| 552 |
); |
| 553 |
} |
| 554 |
|
| 555 |
return ( (Date) value[0] ).before( (Date) value[1] ); |
| 556 |
} |
| 557 |
} |
| 558 |
---- |
| 559 |
==== |
| 560 |
|
| 561 |
As discussed above, the validation target `PARAMETERS` must be configured for a cross-parameter |
| 562 |
validator by using the `@SupportedValidationTarget` annotation. Since a cross-parameter constraint |
| 563 |
could be applied to any method or constructor, it is considered a best practice to check for the |
| 564 |
expected number and types of parameters in the validator implementation. |
| 565 |
|
| 566 |
As with generic constraints, `null` parameters should be considered valid and `@NotNull` on the |
| 567 |
individual parameters should be used to make sure that parameters are not `null`. |
| 568 |
|
| 569 |
[TIP] |
| 570 |
==== |
| 571 |
Similar to class-level constraints, you can create custom constraint violations on single parameters |
| 572 |
instead of all parameters when validating a cross-parameter constraint. Just obtain a node builder |
| 573 |
from the `ConstraintValidatorContext` passed to `isValid()` and add a parameter node by calling |
| 574 |
`addParameterNode()`. In the example you could use this to create a constraint violation on the end |
| 575 |
date parameter of the validated method. |
| 576 |
==== |
| 577 |
|
| 578 |
In rare situations a constraint is both, generic and cross-parameter. This is the case if a |
| 579 |
constraint has a validator class which is annotated with |
| 580 |
`@SupportedValidationTarget({ValidationTarget.PARAMETERS, ValidationTarget.ANNOTATED_ELEMENT})` or if |
| 581 |
it has a generic and a cross-parameter validator class. |
| 582 |
|
| 583 |
When declaring such a constraint on a method which has parameters and also a return value, the |
| 584 |
intended constraint target can't be determined. Constraints which are generic and cross-parameter at |
| 585 |
the same time, must therefore define a member `validationAppliesTo()` which allows the constraint user |
| 586 |
to specify the constraint's target as shown in <<example-dual-cross-parameter-constraint>>. |
| 587 |
|
| 588 |
[[example-dual-cross-parameter-constraint]] |
| 589 |
.Generic and cross-parameter constraint |
| 590 |
==== |
| 591 |
[source, JAVA] |
| 592 |
---- |
| 593 |
package org.hibernate.validator.referenceguide.chapter06.crossparameter; |
| 594 |
|
| 595 |
@Constraint(validatedBy = { |
| 596 |
ScriptAssertObjectValidator.class, |
| 597 |
ScriptAssertParametersValidator.class |
| 598 |
}) |
| 599 |
@Target({ TYPE, FIELD, PARAMETER, METHOD, CONSTRUCTOR, ANNOTATION_TYPE }) |
| 600 |
@Retention(RUNTIME) |
| 601 |
@Documented |
| 602 |
public @interface ScriptAssert { |
| 603 |
|
| 604 |
String message() default "{org.hibernate.validator.referenceguide.chapter06." + |
| 605 |
"crossparameter.ScriptAssert.message}"; |
| 606 |
|
| 607 |
Class<?>[] groups() default { }; |
| 608 |
|
| 609 |
Class<? extends Payload>[] payload() default { }; |
| 610 |
|
| 611 |
String script(); |
| 612 |
|
| 613 |
ConstraintTarget validationAppliesTo() default ConstraintTarget.IMPLICIT; |
| 614 |
} |
| 615 |
---- |
| 616 |
==== |
| 617 |
|
| 618 |
The `@ScriptAssert` constraint has two validators (not shown), a generic and a cross-parameter one and |
| 619 |
thus defines the member `validationAppliesTo()`. The default value `IMPLICIT` allows to derive the |
| 620 |
target automatically in situations where this is possible (e.g. if the constraint is declared on a |
| 621 |
field or on a method which has parameters but no return value). |
| 622 |
|
| 623 |
If the target can not be determined implicitly, it must be set by the user to either `PARAMETERS` or |
| 624 |
`RETURN_VALUE` as shown in <<example-dual-cross-parameter-constraint-usage>>. |
| 625 |
|
| 626 |
[[example-dual-cross-parameter-constraint-usage]] |
| 627 |
.Specifying the target for a generic and cross-parameter constraint |
| 628 |
==== |
| 629 |
[source, JAVA] |
| 630 |
---- |
| 631 |
@ScriptAssert(script = "arg1.size() <= arg0", validationAppliesTo = ConstraintTarget.PARAMETERS) |
| 632 |
public Car buildCar(int seatCount, List<Passenger> passengers) { |
| 633 |
//... |
| 634 |
} |
| 635 |
---- |
| 636 |
==== |
| 637 |
|
| 638 |
[[section-constraint-composition]] |
| 639 |
=== Constraint composition |
| 640 |
|
| 641 |
Looking at the `licensePlate` field of the `Car` class in <<example-car-with-checkcase>>, you see three |
| 642 |
constraint annotations already. In complexer scenarios, where even more constraints could be applied |
| 643 |
to one element, this might become a bit confusing easily. Furthermore, if there was a `licensePlate` |
| 644 |
field in another class, you would have to copy all constraint declarations to the other class as |
| 645 |
well, violating the DRY principle. |
| 646 |
|
| 647 |
You can address this kind of problem by creating higher level constraints, composed from several |
| 648 |
basic constraints. <<example-composed-constraint>> shows a composed constraint annotation which |
| 649 |
comprises the constraints `@NotNull`, `@Size` and `@CheckCase`: |
| 650 |
|
| 651 |
[[example-composed-constraint]] |
| 652 |
.Creating a composing constraint `@ValidLicensePlate` |
| 653 |
==== |
| 654 |
[source, JAVA] |
| 655 |
---- |
| 656 |
package org.hibernate.validator.referenceguide.chapter06.constraintcomposition; |
| 657 |
|
| 658 |
@NotNull |
| 659 |
@Size(min = 2, max = 14) |
| 660 |
@CheckCase(CaseMode.UPPER) |
| 661 |
@Target({ METHOD, FIELD, ANNOTATION_TYPE }) |
| 662 |
@Retention(RUNTIME) |
| 663 |
@Constraint(validatedBy = { }) |
| 664 |
@Documented |
| 665 |
public @interface ValidLicensePlate { |
| 666 |
|
| 667 |
String message() default "{org.hibernate.validator.referenceguide.chapter06." + |
| 668 |
"constraintcomposition.ValidLicensePlate.message}"; |
| 669 |
|
| 670 |
Class<?>[] groups() default { }; |
| 671 |
|
| 672 |
Class<? extends Payload>[] payload() default { }; |
| 673 |
} |
| 674 |
---- |
| 675 |
==== |
| 676 |
|
| 677 |
To create a composed constraint, simply annotate the constraint declaration with its comprising |
| 678 |
constraints. If the composed constraint itself requires a validator, this validator is to be |
| 679 |
specified within the `@Constraint` annotation. For composed constraints which don't need an additional |
| 680 |
validator such as `@ValidLicensePlate`, just set `validatedBy()` to an empty array. |
| 681 |
|
| 682 |
Using the new composed constraint at the `licensePlate` field is fully equivalent to the previous |
| 683 |
version, where the three constraints were declared directly at the field itself: |
| 684 |
|
| 685 |
.Application of composing constraint `ValidLicensePlate` |
| 686 |
==== |
| 687 |
[source, JAVA] |
| 688 |
---- |
| 689 |
package org.hibernate.validator.referenceguide.chapter06.constraintcomposition; |
| 690 |
|
| 691 |
public class Car { |
| 692 |
|
| 693 |
@ValidLicensePlate |
| 694 |
private String licensePlate; |
| 695 |
|
| 696 |
//... |
| 697 |
} |
| 698 |
---- |
| 699 |
==== |
| 700 |
|
| 701 |
The set of `ConstraintViolations` retrieved when validating a `Car` instance will contain an entry for |
| 702 |
each violated composing constraint of the `@ValidLicensePlate` constraint. If you rather prefer a |
| 703 |
single `ConstraintViolation` in case any of the composing constraints is violated, the |
| 704 |
`@ReportAsSingleViolation` meta constraint can be used as follows: |
| 705 |
|
| 706 |
.Using @ReportAsSingleViolation |
| 707 |
==== |
| 708 |
[source, JAVA] |
| 709 |
---- |
| 710 |
//... |
| 711 |
@ReportAsSingleViolation |
| 712 |
public @interface ValidLicensePlate { |
| 713 |
|
| 714 |
String message() default "{org.hibernate.validator.referenceguide.chapter06." + |
| 715 |
"constraintcomposition.ValidLicensePlate.message}"; |
| 716 |
|
| 717 |
Class<?>[] groups() default { }; |
| 718 |
|
| 719 |
Class<? extends Payload>[] payload() default { }; |
| 720 |
} |
| 721 |
---- |
| 722 |
==== |