[英]joi validation based on array object property value
我有一组数据要验证:
{
"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
- 这将定义您的第一个 if 条件。 从那里,您将必须包含另一个.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); //?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.