【问题标题】:How to validate certain fields of a nested json object using JOI validation如何使用 JOI 验证来验证嵌套 json 对象的某些字段
【发布时间】:2019-04-30 00:17:21
【问题描述】:

我需要有关如何使用 JOI 验证来验证嵌套 json 对象的某些字段的帮助。在我的示例中,我有一个包含两个子对象的对象,即clientObjagentObj。我只对验证必需的 username 字段感兴趣,但我不想验证其余字段。如果我只提到该字段,通过删除所有其他字段,在我的架构和 joi.validate() 函数中,我会收到 422 错误。代码如下:

exports.callAuthentication = function (req, res, next) {

    let connectSchema = {
        clientObj: joi.object().keys({
            name: joi.string().min(3).max(38),
            email: joi.string().min(3).max(38),
            language: joi.string().min(3).max(38),
            username: joi.string().min(3).max(38).required(),
            mobile_no: joi.string().min(3).max(38),
            time_zone: joi.string().min(3).max(38),
            system_phone: joi.string().optional().allow('').min(3).max(38),
            phone_no_info: joi.any().optional().allow(''),
            voicemail_pin: joi.string().min(3).max(38),
            display_picture: joi.string().min(3).max(38),
            external_extension: joi.string().min(3).max(38)

        }),
        agentObj: joi.object().keys({
            userId: joi.number(),
            username: joi.string().min(3).max(38).required(),
            name: joi.string().min(3).max(38),
            email: joi.string().min(3).max(38),
            status: joi.string().min(3).max(38),
            role: joi.string().min(3).max(38)
        })
    };

    const data = req.body;

    joi.validate(data, connectSchema, (err) => {
        if (err) {
            // send a 422 error response if validation fails
            res.status(422).json({
                status: 'error',
                message: err.details[0].message
            });
        } else {
            req.body = data;
            next();
        }
    });
}

【问题讨论】:

  • Joi 返回什么错误信息?
  • 收到的错误是 422 Unprocessable Entity。

标签: javascript node.js validation joi


【解决方案1】:

您可以使用{ allowUnknown: true } 允许未知键

const data = {
  clientObj: {
    username: 'username',
    otherProp: 'otherProp'
  },
  agentObj: {
    otherProp2: 'otherProp2'
  }
};

const schema = Joi.object().keys({
  clientObj: Joi.object().keys({
    username: Joi.string().required()
  })
});

Joi.validate(data, schema, { allowUnknown: true }, (err) => {
  console.log(`err with allowUnknown: ${err}`);
});

Joi.validate(data, schema, { allowUnknown: false }, (err) => {
  console.log(`err without allowUnknown: ${err}`);
});
<script src="https://cdn.jsdelivr.net/npm/joi-browser@13.4.0/dist/joi-browser.min.js"></script>

doc

【讨论】:

  • 解决方案有效。感谢 Gabriel 的宝贵意见。
猜你喜欢
  • 2018-02-27
  • 2016-02-19
  • 2021-04-15
  • 2016-09-14
  • 1970-01-01
  • 2018-10-04
  • 2020-02-21
  • 2019-12-13
  • 1970-01-01
相关资源
最近更新 更多