[英]Joi Validation: How to make values in nested json optional?
So I have a nested json something like below, which is a payload structure for api that I am writing 所以我有一个嵌套的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"}
My Joi validation on the payload is : 我对有效负载的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()
})
}
where 哪里
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
and 和
const attributeArraySchema = Joi.array().items(customAttributeObjectSchema).optional();
My question is : With the above Joi validation, if I edit my payload and send my attributes tag like below (i,e., with "values" as empty) 我的问题是:通过上述Joi验证,如果我编辑有效负载并像下面一样发送我的attribute标签(即“ values”为空)
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]
It throws an error saying: 它抛出一个错误,说:
"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"
]
What am I doing wrong here? 我在这里做错了什么? What do I need to do if I need Joi to accept the below:
如果我需要Joi接受以下内容,该怎么办:
"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]
Do something like this 做这样的事情
attributeArraySchema.customAttributes = [];
attributeArraySchema.customAttributes = [
{"id":"CA1","value":""},
{"id":"CA2","value":""}
];
So I resolved this by Changing the following schema definition from 所以我通过更改以下架构定义来解决此问题
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();
To 至
const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().allow('').allow(null)
}).optional();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.