Search code examples
javascriptnode.jsjsonjoi

NPM Joi validation only when key present else ignore


I tried like this, works fine.

const Joi = require('joi');
let schema = Joi.object().keys({
    id:Joi.number().required(),
    first_name: Joi.string().min(2).max(10),
    last_name: Joi.string().min(2).max(10)
});
const req = {
    id: 1,
    first_name: 'AAA',
    last_name: 'BBB'
};

Joi.validate(req, schema, (err) => {
    console.log(err);
});

Incase if req data is

const req = {
    id: 1,
    last_name: 'BBB'
};

It is saying first_name is not allow empty.

How to allow optional keys not to present in json data. When key/property present only apply validation else ignore/skip validation on that property.


Solution

  • Maybe you should try using Joi.assert instead of Joi.validate. Code below works for me.

    import Joi from "joi";
    let schema = Joi.object().keys({
      id: Joi.number().required(),
      first_name: Joi.string().min(2).max(10),
      last_name: Joi.string().min(2).max(10)
    });
    
    const req = {
      id: 1,
      first_name: "AA"
    };
    
    Joi.assert(req, schema);