Joi: Validate depending on another field

Created on 27 May 2014  路  5Comments  路  Source: sideway/joi

I have an api that resembles rpc calls in the form of this schema:

var whitelist = {
  firstObject: ['method1', 'method2'],
  secondObject: ['method1', 'method2']
};

var objects = Object.keys(whitelist);

var schema = Joi.object().keys({
  object: Joi.string().required().valid(objects),
  method: Joi.string().required()
})

Now I want to validate that

  • object is one of the keys of the whitelist, which already works.
  • method is in the whitelist under the correct object entry but I'm not seeing how this could be achieved.

I would appreciate any tips in the right direction.

support

Most helpful comment

No. At some point you have to write code.

All 5 comments

I'm not following what you want to do. Can you post some examples of valid and invalid values?

Sure,

var whitelist = {
  mario: ['run', 'jump'],
  logger: ['print', 'log']
};

// Valid
{
  object: 'mario'
  method: 'run'
}
{
  object: 'logger'
  method: 'print'
}
// Invalid
{
  object: 'mario'
  method: 'print'
}
{
  object: 'logger'
  method: 'jump'
}

I hope these examples makes it a bit clearer.

var schema = Joi.object({
    object: Joi.valid('mario', 'logger'),
    method: Joi.when('object', {
        is: 'mario',
        then: Joi.valid('run', 'jump'),
        otherwise: Joi.valid('print', 'log')
    })
});

Thanks a lot for the quick answer! While this solves the issue in this toy example I'm gonna have probably five or more different objects. Is there any way to solve this a little more elegant than nesting these when conditions in one another?

No. At some point you have to write code.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chrisegner picture chrisegner  路  4Comments

PaunPrashant picture PaunPrashant  路  3Comments

neroaugustus1 picture neroaugustus1  路  4Comments

Taxi4you picture Taxi4you  路  3Comments

jamesdixon picture jamesdixon  路  4Comments