Reputation: 1000
I have this object in json which I would like to validate with a json schema
"reference": {
"lookup" : "opportunity",
"shortreference": 93671,
"guid": "4bb30c46-20ec-e511-9408-005056862bfb"
}
lookup property is mandatory, and then I need at least, either shortreference or guid or both.
{
"reference": {
"type": "object",
"description": "opportunity reference",
"properties": {
"lookup": {
"enum": [
"employee",
"opportunity",
"serviceline",
"account"
]
}
},
"anyOf": [
{
"properties": {
"shortreference": {
"type": "integer"
},
"guid": {
"type": "string"
}
}
}
],
"required": [
"lookup"
]
}
}
EDIT I fixed my issue using the following schema
{
"reference": {
"type": "object",
"required": [
"lookup"
],
"properties": {
"lookup": {
"type": "string",
"enum" : ["opportunity", "employee", "serviceline", "account"]
}
},
"anyOf": [
{
"properties": {
"shortreference": {
"type": "integer"
}
},
"required": [
"shortreference"
]
},
{
"properties": {
"crmguid": {
"type": "string"
}
},
"required": [
"crmguid"
]
},
{
"properties": {
"springim": {
"type": "integer"
}
},
"required": [
"springim"
]
}
]
}
but when I have both elements, all input type aren't typed checked: if "shortreference" : "12345" (a string rather an integer), as soon as the parameter crmguid is provided, the check about type won't be performed. is there a way to force it. (I'm using AJV : https://github.com/epoberezkin/ajv)
Upvotes: 7
Views: 3585
Reputation: 24399
anyOf
will stop validation as soon as it finds one schema that matches. It should work as you expect if you pull all of your property declarations into the root of the schema and just have required
in the anyOf
schemas. That way, all properties will get type checked and anyOf
will stop validation when it finds at least one of the required properties.
{
"reference": {
"type": "object",
"required": ["lookup"],
"properties": {
"lookup": {
"type": "string",
"enum" : ["opportunity", "employee", "serviceline", "account"]
},
"shortreference": { "type": "integer" },
"crmguid": { "type": "string" },
"springim": { "type": "integer" }
},
"anyOf": [
{ "required": ["shortreference"] },
{ "required": ["crmguid"] },
{ "required": ["springim"] }
]
}
}
Upvotes: 10