✔️ JSON Schemahard
12. Conditional rules (if / then)
Write a schema for a payment object with a required "method" that is either "card" or "cash". IF method is "card", THEN "cardNumber" (a string) must also be present. A cash payment needs no card number.
How to approach this
"if" / "then" / "else" express conditional validation. "if" is a schema that's TESTED (not required) against the data; when it matches, "then" must also hold; otherwise "else" (if given). Use "const": "card" inside if's properties to match only card payments, then "then": { "required": ["cardNumber"] }. Because "method" is always required, a "cash" value simply fails the if and skips the then.
schema.json