我正在使用Joi进行对象平视。
假设我的对象是
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"
}
我想对此object1
和object2
添加验证,以使id
的值应该使用global_object
出现在joi
中。
答案 0 :(得分:1)
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
此处输出
> 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
>