'Validation using joi with external schema

So, i'm trying to validate if a field is required given a specific scenario. Like this:

cake: Joi.object().keys({
            flavor: Joi.string().max(45).required(),
            price: Joi.string().length(2).required(),
            topping: Joi.string().length(2).required()
})

and in the same schema i have:

authentication: Joi.object().keys({
      password: Joi.string().max(45).required(),
      login64: Joi.string().max(45).required()
})

and i want to make a validation like:

authentication: Joi.object().keys({
      password: Joi.string().max(45).required(),
      login64: Joi.string().max(45).when('cake.flavor', {
      is: 'chocolate',
      then: Joi.required()

} })

i want to make login64 required if the flavor of the cake is chocolate. But nothing seems to work...



Solution 1:[1]

A Joy reference is by default relative to the parent of the current value, which in your case is authentication. You need to move a couple of levels up (...) in order to reach cake:

login64: Joi.string().max(45).when('...cake.flavor', {
    is: 'chocolate',
    then: Joi.required()
})

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 lbsn