[英]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.