anyOf keyword validates an instance against one or more schemas from its array value. This enables flexible validation where an instance can satisfy different schema alternatives.
Syntax
Behavior
An instance validates successfully againstanyOf if it validates successfully against at least one schema in the array.
- All subschemas are evaluated independently
- At least one subschema must succeed
- If all subschemas fail, the entire
anyOffails - When collecting annotations, all subschemas must be examined to collect annotations from each that validates successfully
Examples
Multiple Type Options
Accept either a string or a number:"hello", 42, 3.14Invalid:
true, null, []
Alternative Object Structures
Accept objects with different required properties:{}, { "name": "John" }
Conditional Formats
Accept different string formats:"[email protected]", "https://example.com", "550e8400-e29b-41d4-a716-446655440000"
Flexible Numeric Ranges
Accept numbers in different valid ranges:5, 0, 10, 95, 100Invalid:
50, -5, 105
Polymorphic Data Structures
Accept different data structure variations:Nullable Values
Accept a specific type or null:"hello", nullInvalid:
"" (empty string), 42
Common Use Cases
- Union types: Allow multiple type alternatives
- Optional formats: Accept data in various valid formats
- Polymorphic objects: Support different object shapes based on discriminator fields
- Fallback validation: Provide alternative validation paths
- Flexible APIs: Accept multiple valid request/response formats
Notes
- When collecting annotations, all subschemas must be examined, even after finding one that validates successfully
- This differs from short-circuit evaluation possible with pure assertion validation
anyOfrequires at least one match, unlikeoneOfwhich requires exactly one- Performance consideration: nested
anyOfcan lead to exponential evaluation paths - Empty arrays are not permitted