JSON Schema - specify field is required based on value of another field
This is definitely possible with version 3 of the draft. Since you have a complete list of allowed countries, then you could do something like this:
{
"type": [
{
"title": "New Zealand (no postcode)",
"type": "object",
"properties": {
"country": {"enum": ["NZ", "NZL", "NEW ZEALAND"]}
}
},
{
"title": "Other countries (require postcode)",
"type": "object",
"properties": {
"country": {"enum": [<all the other countries>]},
"postcode": {"required": true}
}
}
],
"properties": {
"country": {
"type" : "string",
"default" : "AUS"
},
"postcode": {
"type" : "string"
}
}
}
So you actually define two sub-types for your schema, one for countries that require a postcode, and one for countries that do not.
EDIT - the v4 equivalent is extremely similar. Simply rename the top-level "type"
array to "oneOf"
.
If anybody is looking for a solution for draft 4 you can use dependencies
keyword together with a enum
keyword:
{
"type": "object",
"properties": {
"play": {
"type": "boolean"
},
"play-options": {
"type": "string"
}
},
"dependencies": {
"play-options": {
"properties": {
"play": {
"enum": [true]
}
}
}
}
}
In this wayplay-options
will always require play
value to be true
.