Aamer Rasheed
Aamer Rasheed

Reputation: 155

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

I need help regarding how to validate certain fields of a nested json object using JOI validation. In my example I have an object which contains two sub objects i.e. clientObj and agentObj. I'm only interested in validating the username field which is required but I don't want to validate the remaining fields. If I only mention that field, by deleting all other fields, in my schema and joi.validate() function I get 422 error. Code is given below:

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();
        }
    });
}

Upvotes: 0

Views: 4245

Answers (1)

Gabriel Bleu
Gabriel Bleu

Reputation: 10204

You can allow unknown keys with { 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/[email protected]/dist/joi-browser.min.js"></script>

doc

Upvotes: 3

Related Questions