簡體   English   中英

如何使用JOI驗證來驗證嵌套json對象的某些字段

[英]How to validate certain fields of a nested json object using JOI validation

我需要有關如何使用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();
        }
    });
}

您可以使用{ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM