Jakarta Validation API defines a metadata model and API for JavaBean and method validation
npx @tessl/cli install tessl/maven-jakarta-validation--jakarta-validation-api@3.1.00
# Jakarta Validation API
1
2
Jakarta Validation API provides a comprehensive framework for validating JavaBean objects and method parameters through annotations and constraint definitions. It offers a rich set of built-in validation constraints and enables developers to create custom validation logic with detailed error reporting and internationalization capabilities.
3
4
## Package Information
5
6
- **Package Name**: jakarta.validation-api
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>jakarta.validation</groupId>
13
<artifactId>jakarta.validation-api</artifactId>
14
<version>3.1.1</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 jakarta.validation.ConstraintViolation;
25
import jakarta.validation.Valid;
26
import jakarta.validation.Path;
27
import jakarta.validation.Configuration;
28
import jakarta.validation.executable.ExecutableValidator;
29
import jakarta.validation.constraints.*;
30
```
31
32
## Basic Usage
33
34
```java
35
import jakarta.validation.*;
36
import jakarta.validation.constraints.*;
37
import java.util.Set;
38
39
// Define a bean with validation constraints
40
class User {
41
@NotNull
42
@Size(min = 2, max = 50)
43
private String name;
44
45
@Min(18)
46
private int age;
47
48
49
private String email;
50
51
// Constructors, getters, setters...
52
}
53
54
// Validate the bean
55
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
56
Validator validator = factory.getValidator();
57
58
User user = new User("", 15, "invalid-email");
59
Set<ConstraintViolation<User>> violations = validator.validate(user);
60
61
for (ConstraintViolation<User> violation : violations) {
62
System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
63
}
64
```
65
66
## Architecture
67
68
Jakarta Validation API is built around several key components:
69
70
- **Bootstrap API**: Entry point classes (`Validation`, `Configuration`) for setting up validation
71
- **Validation Engine**: Core interfaces (`Validator`, `ValidatorFactory`) for performing validation
72
- **Constraint Framework**: Annotation-based constraints (`@NotNull`, `@Size`, etc.) and custom constraint definition
73
- **Metadata API**: Descriptor interfaces providing validation metadata and introspection
74
- **Method Validation**: Support for validating method parameters and return values
75
- **Value Extraction**: Container element validation for generic types like `List<@NotNull String>`
76
- **SPI**: Service Provider Interface for pluggable validation implementations
77
78
## Capabilities
79
80
### Bootstrap and Configuration
81
82
Core API for setting up and configuring the validation framework with factories and context objects.
83
84
```java { .api }
85
class Validation {
86
static ValidatorFactory buildDefaultValidatorFactory();
87
static GenericBootstrap byDefaultProvider();
88
static <T extends Configuration<T>, U extends ValidationProvider<T>>
89
ProviderSpecificBootstrap<T> byProvider(Class<U> providerType);
90
}
91
92
interface ValidatorFactory extends AutoCloseable {
93
Validator getValidator();
94
ValidatorContext usingContext();
95
MessageInterpolator getMessageInterpolator();
96
TraversableResolver getTraversableResolver();
97
ConstraintValidatorFactory getConstraintValidatorFactory();
98
ParameterNameProvider getParameterNameProvider();
99
ClockProvider getClockProvider();
100
<T> T unwrap(Class<T> type);
101
void close();
102
}
103
104
interface ValidatorContext {
105
ValidatorContext messageInterpolator(MessageInterpolator messageInterpolator);
106
ValidatorContext traversableResolver(TraversableResolver traversableResolver);
107
ValidatorContext constraintValidatorFactory(ConstraintValidatorFactory factory);
108
ValidatorContext parameterNameProvider(ParameterNameProvider parameterNameProvider);
109
ValidatorContext clockProvider(ClockProvider clockProvider);
110
Validator getValidator();
111
}
112
113
interface GenericBootstrap {
114
GenericBootstrap providerResolver(ValidationProviderResolver resolver);
115
Configuration<?> configure();
116
}
117
118
interface ProviderSpecificBootstrap<T extends Configuration<T>> {
119
ProviderSpecificBootstrap<T> providerResolver(ValidationProviderResolver resolver);
120
T configure();
121
}
122
123
interface Configuration<T extends Configuration<T>> {
124
T ignoreXmlConfiguration();
125
T messageInterpolator(MessageInterpolator interpolator);
126
T traversableResolver(TraversableResolver resolver);
127
T constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory);
128
T parameterNameProvider(ParameterNameProvider parameterNameProvider);
129
T clockProvider(ClockProvider clockProvider);
130
T addValueExtractor(ValueExtractor<?> extractor);
131
T addMapping(InputStream stream);
132
T addProperty(String name, String value);
133
MessageInterpolator getDefaultMessageInterpolator();
134
TraversableResolver getDefaultTraversableResolver();
135
ConstraintValidatorFactory getDefaultConstraintValidatorFactory();
136
ParameterNameProvider getDefaultParameterNameProvider();
137
ClockProvider getDefaultClockProvider();
138
BootstrapConfiguration getBootstrapConfiguration();
139
ValidatorFactory buildValidatorFactory();
140
}
141
142
interface BootstrapConfiguration {
143
String getDefaultProviderClassName();
144
List<String> getConstraintValidatorFactoryClassName();
145
List<String> getMessageInterpolatorClassName();
146
List<String> getTraversableResolverClassName();
147
List<String> getParameterNameProviderClassName();
148
List<String> getClockProviderClassName();
149
List<String> getValueExtractorClassNames();
150
Set<String> getConstraintMappingResourcePaths();
151
Map<String, String> getProperties();
152
Set<ExecutableType> getExecutableValidation();
153
boolean isExecutableValidationEnabled();
154
}
155
```
156
157
[Bootstrap and Configuration](./bootstrap-configuration.md)
158
159
### Bean Validation
160
161
Primary validation interface for validating JavaBean objects, properties, and values with comprehensive constraint violation reporting.
162
163
```java { .api }
164
interface Validator {
165
<T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups);
166
<T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups);
167
<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups);
168
BeanDescriptor getConstraintsForClass(Class<?> clazz);
169
ExecutableValidator forExecutables();
170
<T> T unwrap(Class<T> type);
171
}
172
173
interface ConstraintViolation<T> {
174
String getMessage();
175
String getMessageTemplate();
176
T getRootBean();
177
Class<T> getRootBeanClass();
178
Object getLeafBean();
179
Object[] getExecutableParameters();
180
Object getExecutableReturnValue();
181
Path getPropertyPath();
182
Object getInvalidValue();
183
ConstraintDescriptor<?> getConstraintDescriptor();
184
<U> U unwrap(Class<U> type);
185
}
186
```
187
188
[Bean Validation](./bean-validation.md)
189
190
### Built-in Constraints
191
192
Comprehensive set of pre-defined constraint annotations for common validation scenarios including null checks, size validation, numeric ranges, and format validation.
193
194
```java { .api }
195
// Null value constraints
196
@interface NotNull { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
197
@interface Null { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
198
199
// String/Collection constraints
200
@interface NotEmpty { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
201
@interface NotBlank { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
202
@interface Size { int min() default 0; int max() default Integer.MAX_VALUE; String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
203
204
// Numeric constraints
205
@interface Min { long value(); String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
206
@interface Max { long value(); String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
207
@interface DecimalMin { String value(); boolean inclusive() default true; String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
208
@interface DecimalMax { String value(); boolean inclusive() default true; String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
209
@interface Positive { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
210
@interface PositiveOrZero { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
211
@interface Negative { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
212
@interface NegativeOrZero { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
213
@interface Digits { int integer(); int fraction(); String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
214
215
// Date/Time constraints
216
@interface Future { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
217
@interface FutureOrPresent { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
218
@interface Past { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
219
@interface PastOrPresent { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
220
221
// Boolean constraints
222
@interface AssertTrue { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
223
@interface AssertFalse { String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
224
225
// Format constraints
226
@interface Email { String regexp() default ".*"; Pattern.Flag[] flags() default {}; String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
227
@interface Pattern { String regexp(); Pattern.Flag[] flags() default {}; String message() default "..."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
228
229
enum Pattern.Flag {
230
UNIX_LINES, CASE_INSENSITIVE, COMMENTS, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ
231
}
232
```
233
234
[Built-in Constraints](./constraints.md)
235
236
### Custom Constraints
237
238
Framework for defining custom validation constraints through annotations and validator implementations with support for composed constraints.
239
240
```java { .api }
241
@interface Constraint {
242
Class<? extends ConstraintValidator<?, ?>>[] validatedBy();
243
}
244
245
interface ConstraintValidator<A extends Annotation, T> {
246
default void initialize(A constraintAnnotation) {}
247
boolean isValid(T value, ConstraintValidatorContext context);
248
}
249
250
interface ConstraintValidatorContext {
251
void disableDefaultConstraintViolation();
252
String getDefaultConstraintMessageTemplate();
253
ClockProvider getClockProvider();
254
ConstraintViolationBuilder buildConstraintViolationWithTemplate(String messageTemplate);
255
<T> T unwrap(Class<T> type);
256
}
257
258
@interface Valid {}
259
@interface ReportAsSingleViolation {}
260
@interface OverridesAttribute {
261
String constraint();
262
String name();
263
int constraintIndex() default -1;
264
}
265
@interface SupportedValidationTarget {
266
ValidationTarget[] value();
267
}
268
```
269
270
[Custom Constraints](./custom-constraints.md)
271
272
### Method Validation
273
274
Validation support for method parameters, return values, and constructor parameters with cross-parameter constraint capabilities.
275
276
```java { .api }
277
interface ExecutableValidator {
278
<T> Set<ConstraintViolation<T>> validateParameters(T object, Method method, Object[] parameterValues, Class<?>... groups);
279
<T> Set<ConstraintViolation<T>> validateReturnValue(T object, Method method, Object returnValue, Class<?>... groups);
280
<T> Set<ConstraintViolation<T>> validateConstructorParameters(Constructor<? extends T> constructor, Object[] parameterValues, Class<?>... groups);
281
<T> Set<ConstraintViolation<T>> validateConstructorReturnValue(Constructor<? extends T> constructor, T createdObject, Class<?>... groups);
282
}
283
284
enum ExecutableType {
285
IMPLICIT, NONE, CONSTRUCTORS, NON_GETTER_METHODS, GETTER_METHODS, ALL
286
}
287
288
@interface ValidateOnExecution {
289
ExecutableType[] type() default {ExecutableType.IMPLICIT};
290
}
291
```
292
293
[Method Validation](./method-validation.md)
294
295
### Validation Groups
296
297
Group-based validation for conditional constraint application and validation sequencing with group conversion support.
298
299
```java { .api }
300
interface Default {}
301
302
@interface GroupSequence {
303
Class<?>[] value();
304
}
305
306
@interface ConvertGroup {
307
Class<?> from();
308
Class<?> to();
309
}
310
```
311
312
[Validation Groups](./validation-groups.md)
313
314
### Container Element Validation
315
316
Value extraction and validation for generic container types like collections and optionals with type-safe constraint application.
317
318
```java { .api }
319
interface ValueExtractor<T> {
320
void extractValues(T originalValue, ValueReceiver receiver);
321
322
interface ValueReceiver {
323
void value(String nodeName, Object object);
324
void iterableValue(String nodeName, Object object);
325
void indexedValue(String nodeName, int index, Object object);
326
void keyedValue(String nodeName, Object key, Object object);
327
}
328
}
329
330
@interface ExtractedValue {
331
Class<?> type() default Object.class;
332
}
333
334
@interface UnwrapByDefault {}
335
```
336
337
[Container Element Validation](./container-validation.md)
338
339
### Validation Metadata
340
341
Comprehensive metadata API providing descriptors and introspection capabilities for validation constraints and bean structure.
342
343
```java { .api }
344
interface BeanDescriptor extends ElementDescriptor {
345
boolean isBeanConstrained();
346
PropertyDescriptor getPropertyDescriptor(String propertyName);
347
Set<PropertyDescriptor> getConstrainedProperties();
348
MethodDescriptor getMethodDescriptor(String methodName, Class<?>... parameterTypes);
349
Set<MethodDescriptor> getConstrainedMethods(MethodType methodType, MethodType... methodTypes);
350
ConstructorDescriptor getConstructorDescriptor(Class<?>... parameterTypes);
351
Set<ConstructorDescriptor> getConstrainedConstructors();
352
}
353
354
interface ConstraintDescriptor<T extends Annotation> {
355
T getAnnotation();
356
String getMessageTemplate();
357
Set<Class<?>> getGroups();
358
Set<Class<? extends Payload>> getPayload();
359
List<Class<? extends ConstraintValidator<T, ?>>> getConstraintValidatorClasses();
360
Map<String, Object> getAttributes();
361
Set<ConstraintDescriptor<?>> getComposingConstraints();
362
}
363
```
364
365
[Validation Metadata](./metadata.md)
366
367
### Service Provider Interface
368
369
Service Provider Interface (SPI) for pluggable validation provider implementations and bootstrap configuration.
370
371
```java { .api }
372
interface ValidationProvider<T extends Configuration<T>> {
373
T createSpecializedConfiguration(BootstrapState state);
374
Configuration<?> createGenericConfiguration(BootstrapState state);
375
ValidatorFactory buildValidatorFactory(ConfigurationState configurationState);
376
}
377
378
interface BootstrapState {
379
ValidationProviderResolver getValidationProviderResolver();
380
ValidationProviderResolver getDefaultValidationProviderResolver();
381
}
382
383
interface ConfigurationState {
384
boolean isIgnoreXmlConfiguration();
385
MessageInterpolator getMessageInterpolator();
386
Set<InputStream> getMappingStreams();
387
Set<ValueExtractor<?>> getValueExtractors();
388
ConstraintValidatorFactory getConstraintValidatorFactory();
389
TraversableResolver getTraversableResolver();
390
ParameterNameProvider getParameterNameProvider();
391
ClockProvider getClockProvider();
392
Map<String, String> getProperties();
393
}
394
395
interface ValidationProviderResolver {
396
List<ValidationProvider<?>> getValidationProviders();
397
}
398
```
399
400
## Types
401
402
```java { .api }
403
// Core exception hierarchy
404
class ValidationException extends RuntimeException {}
405
class ConstraintViolationException extends ValidationException {
406
Set<ConstraintViolation<?>> getConstraintViolations();
407
}
408
class ConstraintDeclarationException extends ValidationException {}
409
class ConstraintDefinitionException extends ValidationException {}
410
class GroupDefinitionException extends ValidationException {}
411
class NoProviderFoundException extends ValidationException {}
412
class UnexpectedTypeException extends ValidationException {}
413
class ValueExtractorDeclarationException extends ValidationException {}
414
class ValueExtractorDefinitionException extends ValidationException {}
415
416
// Supporting component interfaces
417
interface MessageInterpolator {
418
String interpolate(String messageTemplate, Context context);
419
String interpolate(String messageTemplate, Context context, Locale locale);
420
421
interface Context {
422
ConstraintDescriptor<?> getConstraintDescriptor();
423
Object getValidatedValue();
424
<T> T unwrap(Class<T> type);
425
}
426
}
427
428
interface TraversableResolver {
429
boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType);
430
boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType);
431
}
432
433
interface ParameterNameProvider {
434
List<String> getParameterNames(Constructor<?> constructor);
435
List<String> getParameterNames(Method method);
436
}
437
438
interface ClockProvider {
439
Clock getClock();
440
}
441
442
interface ConstraintValidatorFactory {
443
<T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key);
444
void releaseInstance(ConstraintValidator<?, ?> instance);
445
}
446
447
// Path navigation
448
interface Path extends Iterable<Path.Node> {
449
String toString();
450
451
interface Node {
452
String getName();
453
boolean isInIterable();
454
Integer getIndex();
455
Object getKey();
456
ElementKind getKind();
457
<T extends Path.Node> T as(Class<T> nodeType);
458
String toString();
459
}
460
461
interface BeanNode extends Node {}
462
interface PropertyNode extends Node {}
463
interface MethodNode extends Node {
464
List<Class<?>> getParameterTypes();
465
}
466
interface ConstructorNode extends Node {
467
List<Class<?>> getParameterTypes();
468
}
469
interface ParameterNode extends Node {
470
int getParameterIndex();
471
}
472
interface CrossParameterNode extends Node {}
473
interface ReturnValueNode extends Node {}
474
interface ContainerElementNode extends Node {
475
Class<?> getContainerClass();
476
Integer getTypeArgumentIndex();
477
}
478
}
479
480
// Element classification
481
enum ElementKind {
482
BEAN, PROPERTY, METHOD, CONSTRUCTOR, PARAMETER, CROSS_PARAMETER, RETURN_VALUE, CONTAINER_ELEMENT
483
}
484
485
// Constraint targeting
486
enum ConstraintTarget {
487
IMPLICIT, PARAMETERS, RETURN_VALUE
488
}
489
490
// Validation targeting
491
enum ValidationTarget {
492
ANNOTATED_ELEMENT, PARAMETERS
493
}
494
495
// Method types for metadata
496
enum MethodType {
497
GETTER, NON_GETTER
498
}
499
500
// Value extraction configuration
501
enum Unwrapping {
502
AUTOMATIC, SKIP
503
}
504
505
enum ValidateUnwrappedValue {
506
DEFAULT, SKIP, UNWRAP
507
}
508
509
// Payload marker
510
interface Payload {}
511
```