gpt4 book ai didi

Joi 验证嵌套模式的各个字段

转载 作者:行者123 更新时间:2023-12-02 03:15:27 43 4
gpt4 key购买 nike

我有一个这样的嵌套模式设置:

var schema = Joi.object().keys({
first_name: Joi.string().required(),
last_name: Joi.string().required(),
address: Joi.object().keys({
street: Joi.string().required(),
zip: Joi.number().required(),
state: Joi.string().required(),
country: Joi.string().required()
}).required(),
})

var options = { abortEarly: false };

var result = Joi.validate({}, schema, options);

运行时, result.error将返回消息:
[
{message: '"first_name" is required', path: 'first_name' },
{message: '"last_name" is required', path: 'last_name' },
{message: '"address" is required', path: 'address' }
]

如您所见, address字段未扩展。我不想收到缺少整个地址字段的消息。相反,我想知道地址模式中缺少的单个项目。当我不做 address明确要求,其中的项目不会针对 required() 进行验证根本。嵌套字段验证似乎只适用于整个嵌套架构对象级别,而不适用于架构级别内的单个项目。如何使其与单个嵌套架构项一起使用?

最佳答案

添加“骨架”对象有效。
工作示例 here .

import Joi, {
string,
number,
object
} from "joi";

var schema = object({
first_name: string().required(),
last_name: string().required(),
address: object({
street: string().required(),
zip: number().required(),
state: string().required(),
country: string().required()
})/*.required(), <= Not needed */
})
var skeleton = { address: {} };

var options = { abortEarly: false };

var validate = data => {
var newData = Object.assign({}, skeleton, data);
return Joi.validate( newData, schema, options);
}
console.log(
JSON.stringify(validate({}).error.details, null, 2)
);

结果:
[
{
"message": "\"first_name\" is required",
"path": "first_name",
"type": "any.required",
"context": {
"key": "first_name"
}
},
{
"message": "\"last_name\" is required",
"path": "last_name",
"type": "any.required",
"context": {
"key": "last_name"
}
},
{
"message": "\"street\" is required",
"path": "address.street",
"type": "any.required",
"context": {
"key": "street"
}
},
{
"message": "\"zip\" is required",
"path": "address.zip",
"type": "any.required",
"context": {
"key": "zip"
}
},
{
"message": "\"state\" is required",
"path": "address.state",
"type": "any.required",
"context": {
"key": "state"
}
},
{
"message": "\"country\" is required",
"path": "address.country",
"type": "any.required",
"context": {
"key": "country"
}
}
]

关于Joi 验证嵌套模式的各个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289777/

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