代码之家  ›  专栏  ›  技术社区  ›  Amiga500

joi-验证复杂对象

  •  2
  • Amiga500  · 技术社区  · 6 年前

    我试过了,但没想到:(

    这是我需要验证的对象:

    let body = {
        greeting:
            {
                stringValue: 'Hello !',
                stringListValues: [],
                binaryListValues: [],
                dataType: 'String'
            },
        newsletterId:
            {
                stringValue: '123456789',
                stringListValues: [],
                binaryListValues: [],
                dataType: 'String'
            }
    };
    

    我需要确认 招呼 ,这就是钥匙 斯特林值 这不是空的。其他我不在乎的价值观。

    另外,对于第二个对象 新闻报刊 还有钥匙 斯特林值 这不是空的。其他我不在乎的价值观。

    我提出了只检查根对象的方案:

    const schema = {
        greeting: Joi.required(),
        newsletterId: Joi.required()
    };
    

    我读了很多例子,但是我找不到有这种结构的。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Felix Movee    6 年前

    让我们定义一个模式:

    const schema = Joi.object().keys({
        greeting: Joi.object({
           stringValue: Joi.string().required().empty(['', null]),
           stringListValues: Joi.array().items(Joi.string()),
           binaryListValues: Joi.array().items(Joi.binary())
        }).required(),
        newsletterId: // same as above
    });
    

    像这样测试它:

    Joi.validate(myObjectToTest, schema, function(error, cleanObject){
        console.log(error, cleanObject);
    })
    

    可在此处找到完整的参考资料 https://github.com/hapijs/joi/blob/master/API.md