| 1 |
[[chapter-message-interpolation]] |
| 2 |
== Interpolating constraint error messages |
| 3 |
|
| 4 |
Message interpolation is the process of creating error messages for violated Bean Validation |
| 5 |
constraints. In this chapter you will learn how such messages are defined and resolved and how you |
| 6 |
can plug in custom message interpolators in case the default algorithm is not sufficient for your |
| 7 |
requirements. |
| 8 |
|
| 9 |
[[section-message-interpolation]] |
| 10 |
=== Default message interpolation |
| 11 |
|
| 12 |
Constraint violation messages are retrieved from so called message descriptors. Each constraint |
| 13 |
defines its default message descriptor using the message attribute. At declaration time, the default |
| 14 |
descriptor can be overridden with a specific value as shown in <<example-overriding-message>>. |
| 15 |
|
| 16 |
[[example-overriding-message]] |
| 17 |
.Specifying a message descriptor using the message attribute |
| 18 |
==== |
| 19 |
[source, JAVA] |
| 20 |
---- |
| 21 |
package org.hibernate.validator.referenceguide.chapter04; |
| 22 |
|
| 23 |
public class Car { |
| 24 |
|
| 25 |
@NotNull(message = "The manufacturer name must not be null") |
| 26 |
private String manufacturer; |
| 27 |
|
| 28 |
//constructor, getters and setters ... |
| 29 |
} |
| 30 |
---- |
| 31 |
==== |
| 32 |
|
| 33 |
If a constraint is violated, its descriptor will be interpolated by the validation engine using the |
| 34 |
currently configured `MessageInterpolator`. The interpolated error message can then be retrieved from |
| 35 |
the resulting constraint violation by calling `ConstraintViolation#getMessage()`. |
| 36 |
|
| 37 |
Message descriptors can contain _message parameters_ as well as _message expressions_ which will be |
| 38 |
resolved during interpolation. Message parameters are string literals enclosed in `{}`, while |
| 39 |
message expressions are string literals enclosed in `${}`. The following algorithm is applied during |
| 40 |
method interpolation: |
| 41 |
|
| 42 |
|
| 43 |
. Resolve any message parameters by using them as key for the resource bundle _ValidationMessages_. If |
| 44 |
this bundle contains an entry for a given message parameter, that parameter will be replaced in the |
| 45 |
message with the corresponding value from the bundle. This step will be executed recursively in case |
| 46 |
the replaced value again contains message parameters. The resource bundle is expected to be provided |
| 47 |
by the application developer, e.g. by adding a file named _ValidationMessages.properties_ to the |
| 48 |
classpath. You can also create localized error messages by providing locale specific variations of |
| 49 |
this bundle, such as _$$ValidationMessages_en_US.properties$$_. By default, the JVM's default locale |
| 50 |
(`Locale#getDefault()`) will be used when looking up messages in the bundle. |
| 51 |
|
| 52 |
. Resolve any message parameters by using them as key for a resource bundle containing the standard |
| 53 |
error messages for the built-in constraints as defined in Appendix B of the Bean Validation |
| 54 |
specification. In the case of Hibernate Validator, this bundle is named |
| 55 |
`org.hibernate.validator.ValidationMessages`. If this step triggers a replacement, step 1 is executed |
| 56 |
again, otherwise step 3 is applied. |
| 57 |
|
| 58 |
|
| 59 |
. Resolve any message parameters by replacing them with the value of the constraint annotation member |
| 60 |
of the same name. This allows to refer to attribute values of the constraint (e.g. `Size#min()`) in |
| 61 |
the error message (e.g. "must be at least ${min}"). |
| 62 |
|
| 63 |
|
| 64 |
. Resolve any message expressions by evaluating them as expressions of the Unified Expression |
| 65 |
Language. See <<section-interpolation-with-message-expressions>> to learn more about the usage of |
| 66 |
Unified EL in error messages. |
| 67 |
|
| 68 |
[TIP] |
| 69 |
==== |
| 70 |
You can find the formal definition of the interpolation algorithm in section |
| 71 |
link:http://beanvalidation.org/1.1/spec/#default-resolution-algorithm[5.3.1.1] of the Bean |
| 72 |
Validation specification. |
| 73 |
==== |
| 74 |
|
| 75 |
[[section-special-characters]] |
| 76 |
==== Special characters |
| 77 |
|
| 78 |
Since the characters `{`, `}` and `$` have a special meaning in message descriptors they need to be escaped if you want to use them literally. The following rules apply: |
| 79 |
|
| 80 |
* `\{` is considered as the literal `{` |
| 81 |
* `\}` is considered as the literal `}` |
| 82 |
* `\$` is considered as the literal `$` |
| 83 |
* `\\` is considered as the literal `\` |
| 84 |
|
| 85 |
|
| 86 |
[[section-interpolation-with-message-expressions]] |
| 87 |
==== Interpolation with message expressions |
| 88 |
|
| 89 |
As of Hibernate Validator 5 (Bean Validation 1.1) it is possible to use the Unified Expression |
| 90 |
Language (as defined by link:http://jcp.org/en/jsr/detail?id=341[JSR 341]) in constraint |
| 91 |
violation messages. This allows to define error messages based on conditional logic and also enables |
| 92 |
advanced formatting options. The validation engine makes the following objects available in the EL |
| 93 |
context: |
| 94 |
|
| 95 |
* the attribute values of the constraint mapped to the attribute names |
| 96 |
* the currently validated value (property, bean, method parameter etc.) under the name _validatedValue_ |
| 97 |
* a bean mapped to the name formatter exposing the var-arg method |
| 98 |
`format(String format, Object... args)` which behaves like |
| 99 |
`java.util.Formatter.format(String format, Object... args)`. |
| 100 |
|
| 101 |
The following section provides several examples for using EL expressions in error messages. |
| 102 |
|
| 103 |
==== Examples |
| 104 |
|
| 105 |
<<example-message-descriptors>> shows how to make use of the different options for specifying |
| 106 |
message descriptors. |
| 107 |
|
| 108 |
[[example-message-descriptors]] |
| 109 |
.Specifying message descriptors |
| 110 |
==== |
| 111 |
[source, JAVA] |
| 112 |
---- |
| 113 |
package org.hibernate.validator.referenceguide.chapter04.complete; |
| 114 |
|
| 115 |
public class Car { |
| 116 |
|
| 117 |
@NotNull |
| 118 |
private String manufacturer; |
| 119 |
|
| 120 |
@Size(min = 2, |
| 121 |
max = 14, |
| 122 |
message = "The license plate '${validatedValue}' must be between {min} and {max} characters long" |
| 123 |
) |
| 124 |
private String licensePlate; |
| 125 |
|
| 126 |
@Min(value = 2, |
| 127 |
message = "There must be at least {value} seat${value > 1 ? 's' : ''}" |
| 128 |
) |
| 129 |
private int seatCount; |
| 130 |
|
| 131 |
@DecimalMax(value = "350", |
| 132 |
message = "The top speed ${formatter.format('%1$.2f', validatedValue)} is higher " + |
| 133 |
"than {value}" |
| 134 |
) |
| 135 |
private double topSpeed; |
| 136 |
|
| 137 |
@DecimalMax(value = "100000", message = "Price must not be higher than ${value}") |
| 138 |
private BigDecimal price; |
| 139 |
|
| 140 |
public Car( |
| 141 |
String manufacturer, |
| 142 |
String licensePlate, |
| 143 |
int seatCount, |
| 144 |
double topSpeed, |
| 145 |
BigDecimal price) { |
| 146 |
this.manufacturer = manufacturer; |
| 147 |
this.licensePlate = licensePlate; |
| 148 |
this.seatCount = seatCount; |
| 149 |
this.topSpeed = topSpeed; |
| 150 |
this.price = price; |
| 151 |
} |
| 152 |
|
| 153 |
//getters and setters ... |
| 154 |
} |
| 155 |
---- |
| 156 |
==== |
| 157 |
|
| 158 |
Validating an invalid `Car` instance yields constraint violations with the messages shown by the |
| 159 |
assertions in <<example-expected-error-messages>>: |
| 160 |
|
| 161 |
* the `@NotNull` constraint on the `manufacturer` field causes the error message "may not be null", as |
| 162 |
this is the default message defined by the Bean Validation specification and no specific descriptor |
| 163 |
is given in the message attribute |
| 164 |
|
| 165 |
* the `@Size` constraint on the `licensePlate` field shows the interpolation of message parameters |
| 166 |
(`{min}`, `{max}`) and how to add the validated value to the error message using the EL |
| 167 |
expression `${validatedValue}` |
| 168 |
|
| 169 |
* the `@Min` constraint on `seatCount` demonstrates how use an EL expression with a ternery expression to |
| 170 |
dynamically chose singular or plural form, depending on an attribute of the constraint ("There must |
| 171 |
be at least 1 seat" vs. "There must be at least 2 seats") |
| 172 |
|
| 173 |
* the message for the `@DecimalMax` constraint on `topSpeed` shows how to format the validated |
| 174 |
value using the formatter instance |
| 175 |
|
| 176 |
* finally, the `@DecimalMax` constraint on price shows that parameter interpolation has precedence over |
| 177 |
expression evaluation, causing the `$` sign to show up in front of the maximum price |
| 178 |
|
| 179 |
[TIP] |
| 180 |
==== |
| 181 |
Only actual constraint attributes can be interpolated using message parameters in the form |
| 182 |
`{attributeName}`. When referring to the validated value or custom expression variables added to the |
| 183 |
interpolation context (see <<section-hibernateconstraintvalidatorcontext>>), an EL expression in the |
| 184 |
form `${attributeName}` must be used. |
| 185 |
==== |
| 186 |
|
| 187 |
[[example-expected-error-messages]] |
| 188 |
.Expected error messages |
| 189 |
==== |
| 190 |
[source, JAVA] |
| 191 |
---- |
| 192 |
Car car = new Car( null, "A", 1, 400.123456, BigDecimal.valueOf( 200000 ) ); |
| 193 |
|
| 194 |
String message = validator.validateProperty( car, "manufacturer" ) |
| 195 |
.iterator() |
| 196 |
.next() |
| 197 |
.getMessage(); |
| 198 |
assertEquals( "may not be null", message ); |
| 199 |
|
| 200 |
message = validator.validateProperty( car, "licensePlate" ) |
| 201 |
.iterator() |
| 202 |
.next() |
| 203 |
.getMessage(); |
| 204 |
assertEquals( |
| 205 |
"The license plate must be between 2 and 14 characters long", |
| 206 |
message |
| 207 |
); |
| 208 |
|
| 209 |
message = validator.validateProperty( car, "seatCount" ).iterator().next().getMessage(); |
| 210 |
assertEquals( "There must be at least 2 seats", message ); |
| 211 |
|
| 212 |
message = validator.validateProperty( car, "topSpeed" ).iterator().next().getMessage(); |
| 213 |
assertEquals( "The top speed 400.12 is higher than 350", message ); |
| 214 |
|
| 215 |
message = validator.validateProperty( car, "price" ).iterator().next().getMessage(); |
| 216 |
assertEquals( "Price must not be higher than $100000", message ); |
| 217 |
---- |
| 218 |
==== |
| 219 |
|
| 220 |
[[section-custom-message-interpolation]] |
| 221 |
=== Custom message interpolation |
| 222 |
|
| 223 |
If the default message interpolation algorithm does not fit your requirements it is also possible to |
| 224 |
plug in a custom `MessageInterpolator` implementation. |
| 225 |
|
| 226 |
Custom interpolators must implement the interface `javax.validation.MessageInterpolator`. Note that |
| 227 |
implementations must be thread-safe. It is recommended that custom message interpolators delegate |
| 228 |
final implementation to the default interpolator, which can be obtained via |
| 229 |
`Configuration#getDefaultMessageInterpolator()`. |
| 230 |
|
| 231 |
In order to use a custom message interpolator it must be registered either by configuring it in the |
| 232 |
Bean Validation XML descriptor _META-INF/validation.xml_ (see |
| 233 |
<<section-configuration-validation-xml>>) or by passing it when bootstrapping a `ValidatorFactory` or |
| 234 |
`Validator` (see <<section-validator-factory-message-interpolator>> and |
| 235 |
<<section-configuring-validator>>, respectively). |
| 236 |
|
| 237 |
[[section-resource-bundle-locator]] |
| 238 |
==== `ResourceBundleLocator` |
| 239 |
|
| 240 |
In some use cases you want to use the message interpolation algorithm as defined by the Bean |
| 241 |
Validation specification, but retrieve error messages from other resource bundles than |
| 242 |
_ValidationMessages_. In this situation Hibernate Validator's `ResourceBundleLocator` SPI can help. |
| 243 |
|
| 244 |
The default message interpolator in Hibernate Validator, `ResourceBundleMessageInterpolator`, |
| 245 |
delegates retrieval of resource bundles to that SPI. Using an alternative bundle only requires |
| 246 |
passing an instance of `PlatformResourceBundleLocator` with the bundle name when bootstrapping the |
| 247 |
`ValidatorFactory` as shown in <<example-using-specific-resource-bundle-locator>>. |
| 248 |
|
| 249 |
[[example-using-specific-resource-bundle-locator]] |
| 250 |
.Using a specific resource bundle |
| 251 |
==== |
| 252 |
[source, JAVA] |
| 253 |
---- |
| 254 |
Validator validator = Validation.byDefaultProvider() |
| 255 |
.configure() |
| 256 |
.messageInterpolator( |
| 257 |
new ResourceBundleMessageInterpolator( |
| 258 |
new PlatformResourceBundleLocator( "MyMessages" ) |
| 259 |
) |
| 260 |
) |
| 261 |
.buildValidatorFactory() |
| 262 |
.getValidator(); |
| 263 |
---- |
| 264 |
==== |
| 265 |
|
| 266 |
Of course you also could implement a completely different `ResourceBundleLocator`, which for instance |
| 267 |
returns bundles backed by records in a database. In this case you can obtain the default locator via |
| 268 |
`HibernateValidatorConfiguration#getDefaultResourceBundleLocator()`, which you e.g. could use as |
| 269 |
fall-back for your custom locator. |
| 270 |
|
| 271 |
Besides `PlatformResourceBundleLocator`, Hibernate Validator provides another resource bundle locator |
| 272 |
implementation out of the box, namely `AggregateResourceBundleLocator`, which allows to retrieve error |
| 273 |
messages from more than one resource bundle. You could for instance use this implementation in a |
| 274 |
multi-module application where you want to have one message bundle per module. |
| 275 |
<<example-using-aggregate-resource-bundle-locator>> shows how to use `AggregateResourceBundleLocator`. |
| 276 |
|
| 277 |
[[example-using-aggregate-resource-bundle-locator]] |
| 278 |
.Using `AggregateResourceBundleLocator` |
| 279 |
==== |
| 280 |
[source, JAVA] |
| 281 |
---- |
| 282 |
Validator validator = Validation.byDefaultProvider() |
| 283 |
.configure() |
| 284 |
.messageInterpolator( |
| 285 |
new ResourceBundleMessageInterpolator( |
| 286 |
new AggregateResourceBundleLocator( |
| 287 |
Arrays.asList( |
| 288 |
"MyMessages", |
| 289 |
"MyOtherMessages" |
| 290 |
) |
| 291 |
) |
| 292 |
) |
| 293 |
) |
| 294 |
.buildValidatorFactory() |
| 295 |
.getValidator(); |
| 296 |
---- |
| 297 |
==== |
| 298 |
|
| 299 |
Note that the bundles are processed in the order as passed to the constructor. That means if several |
| 300 |
bundles contain an entry for a given message key, the value will be taken from the first bundle in |
| 301 |
the list containing the key. |
| 302 |
|