【问题标题】:JOI - Validating complex objectJOI - 验证复杂对象
【发布时间】:2019-02-07 16:40:02
【问题描述】:

我试过了,试过了,但还是想不通:(

这是我需要验证的对象:

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

我需要验证是否存在 greeting,并且它具有键 stringValue 并且不为空。其他值我不关心。

另外,对于第二个对象 newsletterId,它也有键 stringValue 并且不为空。其他值我不关心。

我想出只检查根对象,使用这个模式:

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

我阅读了很多示例,但找不到具有这种结构的示例。

【问题讨论】:

    标签: javascript node.js joi


    【解决方案1】:

    让我们定义一个模式:

    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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2013-01-31
    • 2023-03-13
    • 1970-01-01
    • 2018-02-27
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多