Joi: TypeError: Joi.alternatives.try is not a function when nested

Created on 8 Mar 2019  路  3Comments  路  Source: sideway/joi

Context

  • node version: 10.15.2
  • joi version: 14.3.1
  • environment (node, browser): NodeJs v10.15.2, Chrome v72.0.3626.121, macOS Mojave v10.14.3
  • used with (hapi, standalone, ...): standalone and hapi
  • any other relevant information: nope

What are you trying to achieve or the steps to reproduce ?

I'm trying to validate obj, look at the code below.

This doesn't work

const Joi = require('joi');

const schema = Joi.object({
  cron: Joi.string(),
  hourly: Joi.object({
    minute: Joi.alternatives.try(Joi.number(), Joi.array())
  })
});

const obj = {
  hourly: {
    minute: 1
  }
};

const res = Joi.validate(obj, schema);

console.log(res);

This doesn't work too

const schema = Joi.object().keys({
   cron: Joi.string(),
   hourly: Joi.object({
     minute: Joi.alternatives.try(Joi.number(), Joi.array())
   })
});

Which result you had ?

The error

MBP:schema user$ node test.js 
/path/server/schema/test.js:6
    minute: Joi.alternatives.try(Joi.number(), Joi.array())
                                ^

TypeError: Joi.alternatives.try is not a function
    at Object.<anonymous> (/path/server/schema/test.js:6:33)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)

What did you expect ?

Joi validates obj successfully

{ error: null,
  value: { hourly: { minute: 1 } },
  then: [Function: then],
  catch: [Function: catch] }

The short syntax works

const schema = Joi.object({
  cron: Joi.string(),
  hourly: Joi.object({
    minute: [Joi.number(), Joi.array()]
  })
});

Result

{ error: null,
  value: { hourly: { minute: 1 } },
  then: [Function: then],
  catch: [Function: catch] }
non issue

Most helpful comment

@WesTyler yeah, it is a typo. Thanks!

All 3 comments

You're missing the alternatives() method parens: Joi.alternatives.try() vs Joi.alternatives().try()

@WesTyler yeah, it is a typo. Thanks!

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamesdixon picture jamesdixon  路  4Comments

farwayer picture farwayer  路  3Comments

n-sviridenko picture n-sviridenko  路  3Comments

mohamadresaaa picture mohamadresaaa  路  3Comments

Taxi4you picture Taxi4you  路  3Comments