Joi validation of with when() on external property

Viewed 616

I have something like this:

let someCoolString = 'mememe';
const schema = Joi.object({
  someFieldName: Joi.string()
    .when(someCoolString, {
      is: "mememe",
      then: Joi.required(),
      otherwise: Joi.forbidden(),
    })
});

But this obviously doesn't work, as someCoolString is not the Joi.object's property. Any idea of how to check for it?

1 Answers

You can use context:

const schema = Joi.object().keys({
    someFieldName: Joi.number().when('$condition', {
        is: Joi.boolean().valid(true).required(),
        then: Joi.required(),
        otherwise: Joi.forbidden()
    })
});

let someCoolString = 'mememe';
let someCoolString2 = 'not_meme';

function isMeme(str) {
   return str == 'mememe'
};

// error: null
schema.validate({}); 
// someFieldName required
schema.validate({}, {context: {condition: isMeme(someCoolString)}}); 
// someFieldName forbidden
schema.validate({ someField: 10 }, {context: {condition: isMeme(someCoolString2)}}); 
Related