简体   繁体   English

基于根键值的Joi数组对象验证

[英]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 我有一个复杂的场景,我想在这里使用Joi进行验证,示例Joi对象模式

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. 根据opon item_return_flag键值truefalse ,我想更改items.quantity最小值要求。 When true , quantity will be 0 , otherwise it will be 1. 如果为true ,则数量为0,否则为1。

Is there anyway, to control the definition of validation of the object in an array, based on the root object in Joi 无论如何,有没有根据Joi的根对象来控制数组中对象验证的定义

It looks to me like you could, following the API docs , do something like this: 在我看来,您可以按照API文档进行如下操作:

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. 我不确定100%的结构正确无误,但这已经很接近了。 The Joi.alternatives() is provided for just such use cases. 仅针对此类用例提供了Joi.alternatives()

The sample code that will switch the schema based one the parent key item_return_flag . 该示例代码将基于父键item_return_flag之一切换模式。 Schema of the array need to switch based using Joi.altertnatives() 阵列的模式需要使用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)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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