[英]Joi Validation: How to make values in nested json optional?
所以我有一個嵌套的json,如下所示,這是我正在編寫的api的有效負載結構
{"item_id":"1245",
"item_name":"asdffd",
"item_Code":"1244",
"attributes":[{"id":"it1","value":"1"},{"id":"it2","value":"1"}],
"itemUUID":"03741a30-3d62-11e8-b68b-17ec7a13337"}
我對有效負載的Joi驗證是:
validate: {
payload: Joi.object({
item_id: Joi.string().required(),
item_name: Joi.string().required(),
placeId: Joi.string().allow('').allow(null),
itemUUID: Joi.string().allow('').allow(null),
item_Code: Joi.string().required().allow(null),
attributes: Joi.alternatives().try(attributeObjectSchema, attributesArraySchema).optional()
})
}
哪里
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
和
const attributeArraySchema = Joi.array().items(customAttributeObjectSchema).optional();
我的問題是:通過上述Joi驗證,如果我編輯有效負載並像下面一樣發送我的attribute標簽(即“ values”為空)
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]
它拋出一個錯誤,說:
"message": "child \"attributes\" fails because [\"attributes\" must be an object, \"attributes\" at position 0 fails because [child \"value\" fails because [\"value\" is not allowed to be empty]]]",
"validation": {
"source": "payload",
"keys": [
"attributes",
"attributes.0.value"
]
我在這里做錯了什么? 如果我需要Joi接受以下內容,該怎么辦:
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]
做這樣的事情
attributeArraySchema.customAttributes = [];
attributeArraySchema.customAttributes = [
{"id":"CA1","value":""},
{"id":"CA2","value":""}
];
所以我通過更改以下架構定義來解決此問題
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
至
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().allow('').allow(null)
}).optional();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.