gpt4 book ai didi

javascript - 基于数组对象属性值的 joi 验证

转载 作者:行者123 更新时间:2023-12-04 10:03:09 26 4
gpt4 key购买 nike

我有一组数据要验证:

{
"createUser": {
"isCustomer": true or false,
"data": {
"product": [ // sometimes array of object with id : 3
{
"id":46,
"sumInsured":"4562000",
},
{
"id":45,
"sumInsured":"8532000",
},
]
}
}

这些是我们需要验证的以下场景:
1) validate array of objects
2) isCustomer is mandatory when id is 45
3) isCustomer not allowed when id is 3

首先完成:
Joi.object({
data: Joi.array()
.items({
id: Joi.number().valid(3,45,46)
.required(),
sumInsured: Joi.string()
.required()
}),
})

我搜索了很多关于相同的内容,但仍然无法找到相同的解决方案。

任何帮助将非常感激。

提前致谢。

最佳答案

这是第 2 点和第 3 点的组合模式。

您将需要使用方法 .when - 这将定义你的第一个
如果条件。从那里,您将不得不包含另一个 .when添加第二个 if 条件

这样的

.when("data", {
is: <first if condition>,
then: <first if condition do something>
otherwise: .when("data",{
is: <else if>
then: <else if do something>
})
})

要从逻辑上理解上述内容,
这将导致以下
Joi.any().when("data", {
is: <is id 45?>,
then: <is required>
otherwise: Joi.any().when("data",{
is: <is id 3?>
then: <is forbidden>
})
})

测试用例
const test_id_3_ok = {
createUser: {
data: {
product: [
{
id: 3,
},
],
},
},
};

const test_id_46_ok = {
createUser: {
data: {
product: [
{
id: 46,
},
],
},
},
};

const test_id_46_has_customer_ok = {
createUser: {
isCustomer: true,
data: {
product: [
{
id: 46,
},
],
},
},
};

const test_id_46_no_customer_ok = {
createUser: {
data: {
product: [
{
id: 46,
},
],
},
},
};


const test_id_3_has_customer_should_error = {
isCustomer: true,
createUser: {
data: {
product: [
{
id: 3,
},
],
},
},
};

const test_id_45_ok = {
createUser: {
isCustomer: true,
data: {
product: [
{
id: 45,
},
],
},
},
};

const test_id_45_no_customer_should_error = {
createUser: {
data: {
product: [
{
id: 45,
},
],
},
},
};

架构
const dataSchema = Joi.object({
product: Joi.array().items(
Joi.object({
id: Joi.number().valid(3, 45, 46),
})
),
});

const mandatory = (value) =>
Joi.object({
product: Joi.array().items(
Joi.object({
id: Joi.number().valid(value),
})
),
});

const schema = Joi.object({
createUser: Joi.object({
isCustomer: Joi.any().when("data", {
is: mandatory(3),
then: Joi.forbidden(),
otherwise: Joi.any().when("data", {
is: mandatory(45),
then: Joi.bool().required(),
}),
}),

data: dataSchema,
}),
});

schema.validate(test_id_3_ok) //?
schema.validate(test_id_3_has_customer_should_error); //?

schema.validate(test_id_45_ok); //?
schema.validate(test_id_45_no_customer_should_error); //?

schema.validate(test_id_46_ok); //?
schema.validate(test_id_46_has_customer_ok); //?
schema.validate(test_id_46_no_customer_ok); //?

关于javascript - 基于数组对象属性值的 joi 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61733872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com