if, then, and else keywords work together to implement conditional schema application. They allow different validation rules based on whether an instance matches a condition.
Syntax
Behavior
- The
ifschema is evaluated against the instance - If
ifvalidates successfully andthenis present, the instance must also validate againstthen - If
iffails validation andelseis present, the instance must also validate againstelse - The
ifvalidation result does not directly affect overall validation - Annotations from
ifare collected regardless of whetherthenorelseis present
Important Rules
if,then, andelsemust not interact across subschema boundaries (e.g., acrossallOfbranches)- When
ifis absent, boththenandelseare completely ignored - When
thenorelseis absent, there is no default behavior (not treated as empty schema) - Implementations must not evaluate
thenorelsefor validation or annotation if their condition is not met
Examples
Basic Conditional Validation
Require different properties based on a type field:Age-Based Validation
Apply different constraints based on age:Using Only if/then
No else branch - only add requirements when condition is met:Country-Specific Validation
Different postal code formats by country:Product Variant Validation
Different requirements based on product type:Multiple Conditions
Chain conditions for complex logic:Preventing Invalid States
Usethen with not to prevent invalid combinations:
Common Use Cases
- Type-based validation: Different schemas for different types/variants
- Feature flags: Apply constraints based on feature availability
- Tiered systems: Different requirements for different tiers/levels
- Regional variations: Locale or country-specific validation
- State machines: Validate state transitions and state-specific properties
- Progressive requirements: Add requirements as other fields are populated
Notes
- The
ifschema is always evaluated, even ifthenandelseare absent - Annotations from
ifare collected normally, enabling their use by applications - Only the matching branch (
thenorelse) is evaluated for validation - The non-matching branch is completely skipped, including for annotation collection
if/then/elsein oneallOfbranch cannot affect another branch- These keywords enable declarative conditional logic without extension keywords
Best Practices
- Use clear discriminator fields (like
type,kind,version) inifconditions - Consider using
anyOforoneOfwith complete schemas for simple cases - Nest
if/then/elseinelsebranches for multi-way conditions - Keep conditions simple and readable
- Document the business logic behind conditional validation