首页 > 解决方案 > Joi 验证未验证必填字段

问题描述

我有 4 个字段正在尝试使用 Joi 进行验证。我希望以下内容是必需的:要么 firstor secondAnd third or fourth

所以以下其中一项应该通过,但没有其他应该通过:

{first: 'yo', third: true}
// or
{second: 'bro', third: true}
// or
{first: 'yo', fourth: true}
// or
{second: 'bro', fourth: true}

我尝试了以下方法,但它让third并且fourth是空白的。

function validate(data) {
    const schema = Joi.object({
        first: Joi.string(),
        second: Joi.string(),
        third: Joi.boolean(),
        fourth: Joi.boolean(),
    })
        .xor('first', 'second')
        .xor('third', 'fourth');

    return schema.validate(data);
}

标签: javascriptnode.jsjoi

解决方案


推荐阅读