如何使用Joi验证该对象键的值应出现在另一个对象中?

时间:2019-10-24 11:27:50

标签: javascript json validation object joi

我正在使用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"
}

我想对此object1object2添加验证,以使id的值应该使用global_object出现在joi中。

1 个答案:

答案 0 :(得分:1)

可以使用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

此处输出

> 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
>