【问题标题】:Joi - validate property against value in array of objectsJoi - 根据对象数组中的值验证属性
【发布时间】:2018-06-19 08:47:38
【问题描述】:

我正在尝试根据已定义的对象数组验证有效负载中特定属性的值。

例如

有效载荷

{
    a:[1, 2]
}

“a”的值必须是对象数组中定义的id之一(允许多个值)

[
        {
            "id":1,
            "share":{
                "x":100,
                "y":0,
                "z":0
            }
        },
        {
            "id":2,
            "share":{
                "x":90,
                "y":0,
                "z":10
            }
        }
        ....and so on
]

能否请您提供建议,如果这可以通过 Joi 实现?

谢谢,Gowrish

【问题讨论】:

    标签: javascript typescript joi


    【解决方案1】:

    Joi 的 array.validate() 的项目应该可以满足您的需求。

    const Joi = require("joi")
    
    const input = { a: [ 1, 2 ] }
    const objects = [{ id: 1 }, { id: 2 }, { id: 3 }]
    
    const schema = {
      a: Joi.array().items(Joi.any().valid(objects.map(o => o.id)))
    }
    
    const result = Joi.validate(input, schema, (err, result) => {
      if (err) {
        console.error('error:', err)
        return
      }
      console.log('result:', result)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 2020-03-14
      • 2017-08-05
      • 2016-08-05
      • 2016-10-11
      • 1970-01-01
      • 2018-04-15
      相关资源
      最近更新 更多