My JSON payload contains two attributes home_number
, home_name
and at least one attribute always be required. Apart from that those attributes have the following additional constraints.
home_number: type: string, Max length: 4
home_name: type: string, Max length: 50
JSON schema should throw an error if both attributes did not meet requirements.
eg:
valid JSON
{
"home_number": "1234", // valid
}
valid JSON
{
"home_number": null, // invalid
"home_name": "test_home_name" // valid
}
invalid JSON
{
"home_number": "12345", // invalid
"home_name": null // invalid
}
I tried the following JSON schema with draft-07
version using if, then keywords.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"address": {
"$ref": "#/definitions/address",
"properties": {
"house_number": {
"$ref": "#/definitions/address/house_number"
},
"house_name": {
"$ref": "#/definitions/address/house_name"
},
"post_code": {
"$ref": "#/definitions/address/postcode"
}
}
}
},
"required": [
"address"
],
"definitions": {
"address": {
"type": "object",
"properties": {
"postcode": {
"type": "string",
"maxLength": 6
}
},
"anyOf": [
{
"required": [
"house_number"
]
},
{
"required": [
"house_name"
]
}
],
"if": {
"properties": {
"house_name": {
"not": {
"type": "string",
"maxLength": 50
}
}
}
},
"then": {
"properties": {
"house_number": {
"type": "string",
"maxLength": 4
}
}
},
"required": [
"postcode"
]
}
}
}
My question is is there any other/better approach to achieve this
using draft-04
version without using draft-07
if then keywords?