'Joi Validation for nested JSON
I've a nested JSON like below. I need to validate below points in Joi.
- If the Operator is AND or OR, then the args should contain minimum two objects.
- If the Operator is RANGE then the args should contain two objects with keys "from" and "to"
- If the operator is EQ or IN , then args should contains array elements.
{ "operator": "AND", "args": [ { "operator": "RANGE", "name": "column_1", "args": [ { "from": "2021-08-10" }, { "to": "2021-08-11" } ], "type": "string" }, { "operator": "OR", "name": "column_2", "args": [ { "operator": "eq", "name": "column_3", "args": [ "50" ], "type": "number" }, { "operator": "in", "name": "column_4", "args": [ "5", "6" ], "type": "string" } ] } ] }
I'm able to write a custom function using recursion which does this check, But I do not know how to call or perform this in JOI. Below is a pseudo code
function _iterateObject (obj) {
for (const prop in obj) {
if (typeof (obj[prop]) === 'object') {
_iterateObject(obj[prop])
} else {
if (obj[prop] === 'RANGE') {
// do Joi
} else if (obj[prop] === 'AND' || obj[prop] === 'OR' ) {
// do Joi Validation
} else if (obj[prop] === 'IN' || obj[prop] === 'EQ' ) {
// do Joi Validation
}
}
}
}
payload.args.filter(item => {
return _iterateObject(item)
})
Could you please help me how to perform such validations in Joi?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
