Reputation: 10544
I am using Joi for object dalidation.
suppose my objects are
global_object = [
{"id": 1, "name": "Alok"},
{"id": 2, "name": "Ajay"},
{"id": 3, "name": "Ankit"},
]
// valid object because id is present in global_object
object1 = {
"id": 2,
"country": "India"
}
// invalid object because id is not present in global_object
object2 = {
"id": 7,
"country": "India"
}
I want to add validation to this object1
and object2
that value of id
should be present in global_object
using joi
.
Upvotes: 0
Views: 259
Reputation: 10544
This can be possible using Joi.any().valid()
var schema = Joi.object({
id: Joi.any().valid(...global_object.map(e=>e['id'])),
country: Joi.string()
})
console.log(schema.validate(object1)) // valid case
console.log(schema.validate(object2)) // this will show error as its invalid
Here are output
> console.log(schema.validate(object1))
{ value: { id: 2, country: 'India' } }
undefined
> console.log(schema.validate(object2))
{ value: { id: 7, country: 'India' },
error:
{ ValidationError: "id" must be one of [1, 2, 3]
_original: { id: 7, country: 'India' },
details: [ [Object] ] } }
undefined
>
Upvotes: 1