简体   繁体   中英

Joi array Object validation based on root key value

I have a complex scenario that I want to validate using Joi here sample Joi Object Schema

const itemSchema = Joi.object({
    product_id: Joi.string().required(),
    quantity: Joi.number().required().min(0)
});

let objSchema = {
    items: Joi.array().items(itemSchema).required().min(1),
    item_return_flag: Joi.string().optional().valid(true, false)
};

depending opon item_return_flag key value true or false , I want to change the items.quantity min value requirement. When true , quantity will be 0 , otherwise it will be 1.

Is there anyway, to control the definition of validation of the object in an array, based on the root object in Joi

It looks to me like you could, following the API docs , do something like this:

let objSchema = {
     items: Joi.array().items(Joi.object({
         product_id: Joi.string().required(),
         quantity: Joi.alternatives().when('item_return_flag', {
              is: true, then:  Joi.number().required().min(0), 
              otherwise: Joi.number().required().min(1)
         })
     })).required().min(1),
     item_return_flag:  Joi.string().optional().valid(true, false)
};

I'm not 100% sure that's the exact correct structure, but it's close. The Joi.alternatives() is provided for just such use cases.

The sample code that will switch the schema based one the parent key item_return_flag . Schema of the array need to switch based using Joi.altertnatives()

let itemArr = Joi.object({
    product_id: Joi.string().required(),
    quantity: Joi.number().required().min(0)
});

let itemArr2 = Joi.object({
    product_id: Joi.string().required(),
    quantity: Joi.number().required().min(1)
});

let itemSchema = Joi.alternatives()
    .when('item_return_flag', { is: true, then: Joi.array().items(itemArr).required().min(1), otherwise: Joi.array().items(itemArr2).required().min(1)}) ;

let objSchema = {
    items: itemSchema,
    item_return_flag: Joi.string().optional().valid(true, false)
};

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