我有这样的嵌套架构设置:
db->tree
运行时,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
进行验证。嵌套字段验证似乎仅适用于整个嵌套模式对象级别,而不适用于模式级别中的各个项目。如何使其与单独的嵌套架构项一起使用?
答案 0 :(得分:0)
添加"骨架"对象有效。 工作示例here。
data(NamedDataSet)
结果:
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)
);