0
# Hibernate Validator
1
2
Hibernate Validator is the reference implementation of Jakarta Bean Validation 3.1, providing comprehensive annotation-based validation for JavaBeans, method parameters, and return values. It extends the standard Jakarta Validation API with powerful Hibernate-specific features including additional constraint annotations, programmatic configuration, advanced message interpolation, and extensive customization points.
3
4
## Package Information
5
6
- **Package Name**: org.hibernate.validator:hibernate-validator
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>org.hibernate.validator</groupId>
13
<artifactId>hibernate-validator</artifactId>
14
<version>9.0.1.Final</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import jakarta.validation.Validation;
22
import jakarta.validation.Validator;
23
import jakarta.validation.ValidatorFactory;
24
import org.hibernate.validator.HibernateValidator;
25
import org.hibernate.validator.HibernateValidatorConfiguration;
26
import org.hibernate.validator.HibernateValidatorFactory;
27
```
28
29
## Basic Usage
30
31
```java
32
import jakarta.validation.ConstraintViolation;
33
import jakarta.validation.Validation;
34
import jakarta.validation.Validator;
35
import jakarta.validation.ValidatorFactory;
36
import jakarta.validation.constraints.NotNull;
37
import jakarta.validation.constraints.Size;
38
import org.hibernate.validator.HibernateValidator;
39
import org.hibernate.validator.constraints.Length;
40
import java.util.Set;
41
42
// Define a bean with constraints
43
public class User {
44
@NotNull
45
@Size(min = 2, max = 50)
46
private String name;
47
48
@Length(min = 5, max = 100) // Hibernate-specific constraint
49
private String email;
50
51
// Constructor, getters, setters...
52
}
53
54
// Bootstrap Hibernate Validator
55
ValidatorFactory factory = Validation
56
.byProvider(HibernateValidator.class)
57
.configure()
58
.failFast(true) // Stop on first violation
59
.buildValidatorFactory();
60
61
Validator validator = factory.getValidator();
62
63
// Validate an object
64
User user = new User();
65
user.setName("J");
66
user.setEmail("bad");
67
68
Set<ConstraintViolation<User>> violations = validator.validate(user);
69
70
// Process violations
71
for (ConstraintViolation<User> violation : violations) {
72
System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
73
}
74
75
factory.close();
76
```
77
78
## Architecture
79
80
Hibernate Validator's architecture extends Jakarta Bean Validation with additional capabilities:
81
82
### Core Components
83
84
- **ValidationProvider**: Entry point for bootstrapping the validation engine (`HibernateValidator`)
85
- **ValidatorFactory**: Factory for creating `Validator` instances with shared configuration (`HibernateValidatorFactory`)
86
- **Configuration**: Fluent API for configuring the validation engine before factory creation (`HibernateValidatorConfiguration`)
87
- **ValidatorContext**: Per-validator configuration allowing runtime customization (`HibernateValidatorContext`)
88
- **Validator**: The validation engine that validates beans, properties, methods, and constructors
89
90
### Validation Flow
91
92
1. **Bootstrap**: Create a `ValidatorFactory` using `Validation.byProvider(HibernateValidator.class).configure()`
93
2. **Configure**: Set global options (fail-fast, message interpolation, constraint mappings, etc.)
94
3. **Create Validator**: Obtain a `Validator` from the factory
95
4. **Validate**: Call validation methods (`validate()`, `validateProperty()`, `validateValue()`)
96
5. **Process Results**: Handle returned `ConstraintViolation` objects
97
98
### Extension Points
99
100
Hibernate Validator provides extensive customization through:
101
- **Constraint Validators**: Custom validation logic implementing `HibernateConstraintValidator`
102
- **Message Interpolation**: Custom message interpolators and Expression Language feature levels
103
- **Resource Bundle Locators**: Custom resource bundle loading strategies
104
- **Script Evaluators**: Custom script engines for `@ScriptAssert` constraints
105
- **Property Name Providers**: Custom property name resolution for constraint violations
106
- **Locale Resolvers**: Dynamic locale selection for message interpolation
107
108
## Capabilities
109
110
### Configuration and Bootstrap
111
112
Bootstrap and configure Hibernate Validator with standard and Hibernate-specific options including fail-fast modes, method constraint validation rules, Expression Language feature levels, temporal validation tolerance, and predefined scope validation.
113
114
```java { .api }
115
/**
116
* Default implementation of ValidationProvider for full-scope validation.
117
*/
118
class HibernateValidator implements ValidationProvider<HibernateValidatorConfiguration> {
119
HibernateValidatorConfiguration createSpecializedConfiguration(BootstrapState state);
120
Configuration<?> createGenericConfiguration(BootstrapState state);
121
ValidatorFactory buildValidatorFactory(ConfigurationState configurationState);
122
}
123
124
/**
125
* Configuration interface for standard Hibernate Validator usage.
126
* Extends Jakarta Validation Configuration with Hibernate-specific options.
127
*/
128
interface HibernateValidatorConfiguration
129
extends BaseHibernateValidatorConfiguration<HibernateValidatorConfiguration> {
130
}
131
132
/**
133
* Factory for creating Validator instances with Hibernate-specific extensions.
134
*/
135
interface HibernateValidatorFactory extends ValidatorFactory {
136
/**
137
* Create a ValidatorContext with Hibernate-specific configuration options.
138
*/
139
HibernateValidatorContext usingContext();
140
141
ScriptEvaluatorFactory getScriptEvaluatorFactory();
142
Duration getTemporalValidationTolerance();
143
GetterPropertySelectionStrategy getGetterPropertySelectionStrategy();
144
PropertyNodeNameProvider getPropertyNodeNameProvider();
145
}
146
147
/**
148
* Context for creating Validator instances with per-validator configuration.
149
*/
150
interface HibernateValidatorContext extends ValidatorContext {
151
HibernateValidatorContext failFast(boolean failFast);
152
HibernateValidatorContext allowOverridingMethodAlterParameterConstraint(boolean allow);
153
HibernateValidatorContext allowMultipleCascadedValidationOnReturnValues(boolean allow);
154
HibernateValidatorContext allowParallelMethodsDefineParameterConstraints(boolean allow);
155
HibernateValidatorContext enableTraversableResolverResultCache(boolean enabled);
156
HibernateValidatorContext temporalValidationTolerance(Duration temporalValidationTolerance);
157
HibernateValidatorContext constraintValidatorPayload(Object constraintValidatorPayload);
158
HibernateValidatorContext showValidatedValuesInTraceLogs(boolean enabled);
159
HibernateValidatorContext failFastOnPropertyViolation(boolean failFastOnPropertyViolation);
160
}
161
```
162
163
[Configuration and Bootstrap](./configuration.md)
164
165
### Built-in Constraint Annotations
166
167
Extensive collection of constraint annotations beyond standard Jakarta Validation, including string constraints (`@Length`, `@UUID`, `@CodePointLength`), financial validators (`@CreditCardNumber`, `@BitcoinAddress`), product identifiers (`@ISBN`, `@EAN`), time constraints (`@DurationMin`, `@DurationMax`), script-based validation (`@ScriptAssert`), and country-specific validators for Brazil, Poland, Russia, and Korea.
168
169
```java { .api }
170
/**
171
* String length constraint (Hibernate-specific alternative to @Size).
172
*/
173
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
174
@Retention(RUNTIME)
175
@Constraint(validatedBy = {})
176
@interface Length {
177
String message() default "{org.hibernate.validator.constraints.Length.message}";
178
Class<?>[] groups() default {};
179
Class<? extends Payload>[] payload() default {};
180
int min() default 0;
181
int max() default Integer.MAX_VALUE;
182
}
183
184
/**
185
* Credit card number validation using Luhn algorithm.
186
*/
187
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
188
@Retention(RUNTIME)
189
@Constraint(validatedBy = {})
190
@interface CreditCardNumber {
191
String message() default "{org.hibernate.validator.constraints.CreditCardNumber.message}";
192
Class<?>[] groups() default {};
193
Class<? extends Payload>[] payload() default {};
194
boolean ignoreNonDigitCharacters() default false;
195
}
196
197
/**
198
* URL validation with protocol, host, and port constraints.
199
*/
200
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
201
@Retention(RUNTIME)
202
@Constraint(validatedBy = {})
203
@interface URL {
204
String message() default "{org.hibernate.validator.constraints.URL.message}";
205
Class<?>[] groups() default {};
206
Class<? extends Payload>[] payload() default {};
207
String protocol() default "";
208
String host() default "";
209
int port() default -1;
210
String regexp() default ".*";
211
Pattern.Flag[] flags() default {};
212
}
213
214
/**
215
* Duration minimum constraint.
216
*/
217
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
218
@Retention(RUNTIME)
219
@Constraint(validatedBy = {})
220
@interface DurationMin {
221
String message() default "{org.hibernate.validator.constraints.time.DurationMin.message}";
222
Class<?>[] groups() default {};
223
Class<? extends Payload>[] payload() default {};
224
long days() default 0;
225
long hours() default 0;
226
long minutes() default 0;
227
long seconds() default 0;
228
long millis() default 0;
229
long nanos() default 0;
230
boolean inclusive() default true;
231
}
232
```
233
234
[Built-in Constraints](./constraints.md)
235
236
### Programmatic Constraint Configuration
237
238
Fluent API for defining constraints programmatically without annotations, supporting type, property, method, constructor, parameter, and return value constraints with full feature parity to annotation-based configuration.
239
240
```java { .api }
241
/**
242
* Programmatic constraint mapping interface.
243
*/
244
interface ConstraintMapping {
245
/**
246
* Start defining constraints for a bean class.
247
*/
248
<C> TypeConstraintMappingContext<C> type(Class<C> type);
249
250
/**
251
* Define custom constraint validators for a constraint annotation.
252
*/
253
<A extends Annotation> ConstraintDefinitionContext<A> constraintDefinition(Class<A> annotationClass);
254
}
255
256
/**
257
* Base class for constraint definitions in programmatic API.
258
*/
259
abstract class ConstraintDef<C extends ConstraintDef<C, A>, A extends Annotation>
260
extends AnnotationDef<C, A> {
261
C message(String message);
262
C groups(Class<?>... groups);
263
C payload(Class<? extends Payload>... payload);
264
}
265
266
/**
267
* Generic constraint definition for constraints without specific type-safe class.
268
*/
269
class GenericConstraintDef<A extends Annotation> extends ConstraintDef<GenericConstraintDef<A>, A> {
270
// Generic constraint definition
271
}
272
```
273
274
[Programmatic Configuration](./programmatic-config.md)
275
276
### Custom Constraint Validators
277
278
Hibernate-specific extensions to the constraint validator API providing enhanced initialization context, dynamic message parameters, expression language variables, dynamic payloads, and constraint validator payload access.
279
280
```java { .api }
281
/**
282
* Hibernate Validator extension to ConstraintValidator.
283
*/
284
interface HibernateConstraintValidator<A extends Annotation, T>
285
extends ConstraintValidator<A, T> {
286
/**
287
* Initialize with enhanced Hibernate-specific context.
288
*/
289
default void initialize(
290
ConstraintDescriptor<A> constraintDescriptor,
291
HibernateConstraintValidatorInitializationContext initializationContext
292
) {
293
initialize(constraintDescriptor.getAnnotation());
294
}
295
}
296
297
/**
298
* Hibernate-specific constraint validator context with additional capabilities.
299
*/
300
interface HibernateConstraintValidatorContext extends ConstraintValidatorContext {
301
/**
302
* Add named message parameter for interpolation.
303
*/
304
HibernateConstraintValidatorContext addMessageParameter(String name, Object value);
305
306
/**
307
* Add expression language variable for message interpolation.
308
*/
309
HibernateConstraintValidatorContext addExpressionVariable(String name, Object value);
310
311
/**
312
* Set dynamic payload for constraint violation.
313
*/
314
HibernateConstraintValidatorContext withDynamicPayload(Object payload);
315
316
/**
317
* Get constraint validator payload passed during configuration.
318
*/
319
<C> C getConstraintValidatorPayload(Class<C> type);
320
321
/**
322
* Build constraint violation with Hibernate-specific features.
323
*/
324
HibernateConstraintViolationBuilder buildConstraintViolationWithTemplate(String messageTemplate);
325
}
326
327
/**
328
* Enhanced constraint violation containing dynamic payload.
329
*/
330
interface HibernateConstraintViolation<T> extends ConstraintViolation<T> {
331
/**
332
* Get dynamic payload set via HibernateConstraintValidatorContext.
333
*/
334
<C> C getDynamicPayload(Class<C> type);
335
}
336
```
337
338
[Custom Constraint Validators](./constraint-validation.md)
339
340
### Message Interpolation
341
342
Advanced message interpolation with Expression Language support, configurable feature levels for security, custom locale resolution, resource bundle aggregation, and parameter-only interpolation for EL-free environments.
343
344
```java { .api }
345
/**
346
* Resource bundle-backed message interpolator with Expression Language support.
347
*/
348
class ResourceBundleMessageInterpolator extends AbstractMessageInterpolator {
349
ResourceBundleMessageInterpolator();
350
ResourceBundleMessageInterpolator(ResourceBundleLocator userResourceBundleLocator);
351
ResourceBundleMessageInterpolator(
352
ResourceBundleLocator userResourceBundleLocator,
353
ResourceBundleLocator contributorResourceBundleLocator
354
);
355
ResourceBundleMessageInterpolator(
356
ResourceBundleLocator userResourceBundleLocator,
357
ResourceBundleLocator contributorResourceBundleLocator,
358
boolean cachingEnabled
359
);
360
}
361
362
/**
363
* Message interpolator without EL support (parameter values only).
364
*/
365
class ParameterMessageInterpolator extends AbstractMessageInterpolator {
366
ParameterMessageInterpolator();
367
}
368
369
/**
370
* Expression Language feature level for security control.
371
*/
372
enum ExpressionLanguageFeatureLevel {
373
DEFAULT, // Context-dependent default
374
NONE, // No EL interpolation
375
VARIABLES, // Only injected variables, formatter, and ResourceBundles
376
BEAN_PROPERTIES, // Variables plus bean properties (spec-compliant minimum)
377
BEAN_METHODS; // Bean properties plus method execution (security risk!)
378
379
static ExpressionLanguageFeatureLevel of(String level);
380
static ExpressionLanguageFeatureLevel interpretDefaultForConstraints(ExpressionLanguageFeatureLevel level);
381
static ExpressionLanguageFeatureLevel interpretDefaultForCustomViolations(ExpressionLanguageFeatureLevel level);
382
}
383
```
384
385
[Message Interpolation](./message-interpolation.md)
386
387
### Property Path Navigation
388
389
Hibernate-specific extensions to Jakarta Validation property path nodes, providing access to actual property and container element values during validation for enhanced error reporting and debugging.
390
391
```java { .api }
392
/**
393
* Property node with value access (Hibernate extension).
394
*/
395
interface PropertyNode extends jakarta.validation.Path.PropertyNode {
396
/**
397
* Get the value of the bean property represented by this node.
398
*/
399
Object getValue();
400
}
401
402
/**
403
* Container element node with value access (Hibernate extension).
404
*/
405
interface ContainerElementNode extends jakarta.validation.Path.ContainerElementNode {
406
/**
407
* Get the value of the container element represented by this node.
408
*/
409
Object getValue();
410
}
411
```
412
413
[Property Path Navigation](./path-navigation.md)
414
415
### Resource Bundle Loading
416
417
Multiple resource bundle locator implementations supporting platform resource bundles, aggregation of multiple bundles, caching, and delegation patterns for flexible message source configuration.
418
419
```java { .api }
420
/**
421
* Default platform resource bundle locator.
422
*/
423
class PlatformResourceBundleLocator implements ResourceBundleLocator {
424
PlatformResourceBundleLocator(String bundleName);
425
PlatformResourceBundleLocator(String bundleName, ClassLoader classLoader);
426
ResourceBundle getResourceBundle(Locale locale);
427
}
428
429
/**
430
* Aggregates multiple resource bundle locators.
431
*/
432
class AggregateResourceBundleLocator implements ResourceBundleLocator {
433
AggregateResourceBundleLocator(List<ResourceBundleLocator> resourceBundleLocators);
434
ResourceBundle getResourceBundle(Locale locale);
435
}
436
437
/**
438
* Caching resource bundle locator wrapper.
439
*/
440
class CachingResourceBundleLocator implements ResourceBundleLocator {
441
CachingResourceBundleLocator(ResourceBundleLocator delegate);
442
ResourceBundle getResourceBundle(Locale locale);
443
}
444
```
445
446
[Resource Bundle Loading](./resource-loading.md)
447
448
### Service Provider Interfaces
449
450
Comprehensive SPI for extending Hibernate Validator including constraint mapping contributors, dynamic group sequence providers, custom locale resolvers, property node name providers, getter property selection strategies, resource bundle locators, and script evaluator factories.
451
452
```java { .api }
453
/**
454
* Contributes constraint mappings to validator configuration.
455
*/
456
interface ConstraintMappingContributor {
457
void createConstraintMappings(ConstraintMappingBuilder builder);
458
459
interface ConstraintMappingBuilder {
460
ConstraintMapping addConstraintMapping();
461
}
462
}
463
464
/**
465
* Provides default group sequence dynamically at validation time.
466
*/
467
interface DefaultGroupSequenceProvider<T> {
468
List<Class<?>> getValidationGroups(T object);
469
}
470
471
/**
472
* Resolves locale for message interpolation.
473
*/
474
interface LocaleResolver {
475
Locale resolve(LocaleResolverContext context);
476
}
477
478
/**
479
* Resolves property node names in validation paths.
480
*/
481
interface PropertyNodeNameProvider {
482
String getName(Property property);
483
}
484
485
/**
486
* Defines strategy for detecting JavaBean getters.
487
*/
488
interface GetterPropertySelectionStrategy {
489
Optional<String> getProperty(ConstrainableExecutable executable);
490
List<String> getGetterMethodNameCandidates(String propertyName);
491
}
492
493
/**
494
* Factory for creating script evaluators.
495
*/
496
interface ScriptEvaluatorFactory {
497
ScriptEvaluator getScriptEvaluatorByLanguageName(String languageName);
498
void clear();
499
}
500
```
501
502
[Service Provider Interfaces](./spi.md)
503
504
## Types
505
506
### Configuration Property Constants
507
508
```java { .api }
509
/**
510
* Configuration property names for Hibernate Validator.
511
* Defined in BaseHibernateValidatorConfiguration interface.
512
*/
513
class ConfigurationProperties {
514
String FAIL_FAST = "hibernate.validator.fail_fast";
515
String ALLOW_PARAMETER_CONSTRAINT_OVERRIDE = "hibernate.validator.allow_parameter_constraint_override";
516
String ALLOW_MULTIPLE_CASCADED_VALIDATION_ON_RESULT = "hibernate.validator.allow_multiple_cascaded_validation_on_result";
517
String ALLOW_PARALLEL_METHODS_DEFINE_PARAMETER_CONSTRAINTS = "hibernate.validator.allow_parallel_method_parameter_constraint";
518
String CONSTRAINT_MAPPING_CONTRIBUTORS = "hibernate.validator.constraint_mapping_contributors";
519
String ENABLE_TRAVERSABLE_RESOLVER_RESULT_CACHE = "hibernate.validator.enable_traversable_resolver_result_cache";
520
String SCRIPT_EVALUATOR_FACTORY_CLASSNAME = "hibernate.validator.script_evaluator_factory";
521
String TEMPORAL_VALIDATION_TOLERANCE = "hibernate.validator.temporal_validation_tolerance";
522
String GETTER_PROPERTY_SELECTION_STRATEGY_CLASSNAME = "hibernate.validator.getter_property_selection_strategy";
523
String PROPERTY_NODE_NAME_PROVIDER_CLASSNAME = "hibernate.validator.property_node_name_provider";
524
String LOCALE_RESOLVER_CLASSNAME = "hibernate.validator.locale_resolver";
525
String CONSTRAINT_EXPRESSION_LANGUAGE_FEATURE_LEVEL = "hibernate.validator.constraint_expression_language_feature_level";
526
String CUSTOM_VIOLATION_EXPRESSION_LANGUAGE_FEATURE_LEVEL = "hibernate.validator.custom_violation_expression_language_feature_level";
527
String SHOW_VALIDATED_VALUE_IN_TRACE_LOGS = "hibernate.validator.show_validated_value_in_trace_logs";
528
String FAIL_FAST_ON_PROPERTY_VIOLATION = "hibernate.validator.fail_fast_on_property_violation";
529
}
530
```
531
532
### Incubating Annotation
533
534
```java { .api }
535
/**
536
* Marks API elements as incubating (subject to incompatible changes).
537
*/
538
@Documented
539
@Retention(RetentionPolicy.CLASS)
540
@interface Incubating {
541
}
542
```
543
544
### Hibernate Validator Permission
545
546
```java { .api }
547
package org.hibernate.validator;
548
549
import java.security.BasicPermission;
550
551
/**
552
* Hibernate Validator specific implementation of BasicPermission.
553
* Thread-safe and immutable.
554
*
555
* @deprecated This permission will be removed in future versions as
556
* Hibernate Validator no longer relies on SecurityManager.
557
*/
558
@Deprecated(forRemoval = true)
559
class HibernateValidatorPermission extends BasicPermission {
560
/**
561
* Permission to access private members for validation.
562
*/
563
static final HibernateValidatorPermission ACCESS_PRIVATE_MEMBERS;
564
565
/**
566
* Create permission with name.
567
*
568
* @param name permission name
569
*/
570
HibernateValidatorPermission(String name);
571
572
/**
573
* Create permission with name and actions.
574
*
575
* @param name permission name
576
* @param actions permission actions
577
*/
578
HibernateValidatorPermission(String name, String actions);
579
}
580
```
581