简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM