oneOf keyword validates an instance against exactly one schema from its array value. This enforces mutual exclusivity between schema alternatives.
Syntax
Behavior
An instance validates successfully againstoneOf if it validates successfully against exactly one schema in the array.
- All subschemas are evaluated independently
- Exactly one subschema must succeed
- If zero or more than one subschema succeeds, the entire
oneOffails - This enforces mutual exclusivity between alternatives
Examples
Discriminated Types
Require objects with mutually exclusive type indicators:anyOf)
Exclusive Number Ranges
Require numbers in one of several non-overlapping ranges:5, 15, 25Invalid:
10 (matches two schemas), -5, 35
Version-Specific Schemas
Enforce different schemas based on version field:Payment Method Selection
Require exactly one payment method:Invalid: Object with zero or multiple payment methods
Boolean XOR Logic
Implement exclusive-OR behavior:Common Use Cases
- Discriminated unions: Enforce mutually exclusive object types
- Non-overlapping ranges: Validate values in exclusive ranges
- Single selection: Require exactly one option from a set
- Version enforcement: Apply different schemas based on version
- API variants: Support different but exclusive API formats
Comparison with Other Keywords
| Keyword | Required Matches | Use Case |
|---|---|---|
allOf | All schemas | Combine constraints |
anyOf | At least one | Union types |
oneOf | Exactly one | Exclusive choice |
Notes
- Unlike
anyOf, validation fails if more than one subschema matches - This can catch unintended overlaps in schema design
- Performance consideration: all subschemas must be evaluated to count matches
- Nested
oneOfcan lead to exponential evaluation paths - Empty arrays are not permitted
- Use discriminator fields (like
typeorversion) to make schemas truly exclusive