'Joi apply different validation on nested object based on parent key

i just started using Joi and kind of lost about this case and don't know if its even possible the way i am going about it.

i have an object that has multiple keys with each key being a nested object with some shared props between them, something like this.

{
  a: {
    x: true,
    y: ''
  },
  b: {
    x: false
  }
}

i am trying to make Joi validate that y exists when my parent is a and it should validate that y doesn't exist otherwise.

i am using pattern like this

const allowedKeys ['a', 'b']
Joi.object().pattern(
    Joi.string().valid(...allowedKeys),
    Joi.object().keys({
      x: Joi.boolean(),
      y: // this should exist if i am inside `a` but shouldn't otherwise
    })
  ),

i have done a few searches and tried using alternatives, ref and when and a combo of them but i can't find a way to test the current parent key's value.

am i going about this correctly or should i follow another pattern to get what i need ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source