JSON and data guides

JSON Schema conditionals: require fields only when needed

Apply if/then and dependentRequired without making absent selector fields activate a branch accidentally.

Nav Tools ·

Make the selector mandatory in if

A properties constraint can pass when its property is absent. Put required inside if when the branch should apply only to an explicit selector.

This schema requires a path only when mode is file. An empty object does not activate that condition.

{"type":"object","if":{"properties":{"mode":{"const":"file"}},"required":["mode"]},
 "then":{"required":["path"]},"properties":{"path":{"type":"string","minLength":1}}}

Run three distinct cases

Test an absent mode, mode file without path, and mode file with a nonempty path. These should pass, fail and pass respectively.

If mode itself is globally required, add a separate root required rule. Conditional activation and global completeness are separate decisions.

Use dependencies for presence relationships

dependentRequired says that presence of one property requires others, regardless of its value. It does not make the dependency symmetric.

To require both fields whenever either appears, declare both directions. Use if/then instead when the field value determines the requirement.

{"dependentRequired":{"start":["end"],"end":["start"]}}
Neither field is globally required.

Validate meaning after shape

Dependencies can require start and end but cannot by themselves prove end is later than start. Schema acceptance is only one layer.

Validate cross-field business rules in application code and keep fixtures for both shape errors and semantic errors.

References

← JSON and data guides