Reputation: 3
I need to apply a validation to an array, based on a property from a parent object. ex:
{
"data": [{
"account": {
"type": "special"
},
"customers": [{
"email": "[email protected]",
"phoneNumbers": [
"913 449-6602"
]
}]
}]
}
If account === 'special', then email and phoneNumbers need to be present inside customers. (email != null, and phoneNumbers.length > 1. no regex validation necessary) else, i dont care.
I've sifted through dozens of previous questions and haven't found anything that solves this use case.
I am curious if applying a definition conditionally is possible? ex: Apply one definition when account.type is "special", another when it isn't. I don't think "If-then-contains" works, since I need the validation applied to ALL customers, not just one.
thanks in advance and let me know if more clarification needed.
relevant Q's that helped:
jsonSchema attribute conditionally required depends on parent object
jsonSchema attribute conditionally required
Upvotes: 0
Views: 278
Reputation: 53966
You can apply a condition to all items - just wrap it in the items
keyword:
{
"if": {
"required": ["account"],
"properties": {
"account": {
"required": ["type"],
"properties": {
"type": { "const": "special" }
}
}
}
},
"then": {
"required": ["customers"],
"properties": {
"customers": {
"type": "array",
"items": {
... check email and phoneNumbers here ...
}
}
}
}
}
In pseudocode: if the account type is "special", then apply the extra definition to all customer items.
More info here:
Upvotes: 1