Joi validation - how to make field validation based on the array value?

Viewed 203

I've been trying to implement the following logic:

if methods array includes object { type: 0 }

then grade field is requires

else grade field is optional

const methodTypeSchema = Joi.object({
  type: Joi.number(),
});

export const schema = Joi.object({
  methods: Joi.array().items(methodTypeSchema),
  grade: Joi.string().when('methods', {
    is: Joi.array().has(Joi.object({ type: 0 })),
    then: Joi.required(),
    otherwise: Joi.optional(),
  }),
});

I'll be grateful for the help.

1 Answers

hm, now it seems working... my mistake was that instead of default Joi.string() I used some custom functions

Related