Warm tip: This article is reproduced from stackoverflow.com, please click
express joi nodes hapijs

Joi validate array of objects with when condition

发布于 2020-03-27 15:44:11

First of all, sorry for bad English.

I can't find any docs about this.

WHAT I WANT TO DO

const docs = {
  type: 'a', // ['a',' 'b', 'c'] is available.
  items: [
    {
      a: 123,
      b: 100 // => This value only available when type is 'a' or 'b'. otherwise, forbidden.
    }
  ]
};

MY JOI SCHEMA(NOT WORKED)

Joi.object({
  type: Joi.string().valid('a', 'b', 'c').required(),
  items: Joi.array()
    .items(
      Joi.object({
        a: Joi.number().required()
        b: Joi.number()
      })
    )
    .when('type', {
      is: Joi.string().valid('a', 'b'),
      then: Joi.array().items(Joi.object({ b: Joi.number().required() })),
      otherwise: Joi.array().items(Joi.object({ b: Joi.number().forbidden() }))
    })
})

This code is not working correctly. When type is 'c', it validate passed.

How can I fix this?

Questioner
Wooyoung Tyler Kim
Viewed
104
Vinil Prabhu 2020-01-31 17:26

You have added .items() to items: Joi.array() which overrides the .when() condition, try using

Joi.object({
    type: Joi.string().valid('a', 'b', 'c').required(),
    items: Joi.array()
        .when('type', {
            is: Joi.string().valid('a', 'b'),
            then: Joi.array().items(Joi.object({
                a: Joi.number().required(),
                b: Joi.number().required()
            })),
            otherwise: Joi.array().items(Joi.object({
                a: Joi.number().required()
            }))
        })
})

example