问题描述
我刚遇到这行代码,我必须处理:
Joi.array().label('Emails').items(Joi.string()).required()
我特别不明白 .label('Emails')
在做什么,所以,我点击了文档:
覆盖错误消息中的键名。
name - the name of the key.
const 架构 = { first_name: Joi.string().label('First Name') };
这对我来说没有任何意义。因为,First Name
、Emails
是可以传递的特定参数吗?它压倒什么?我们还可以传递哪些其他参数等等。这个方法有什么特别的作用?
解决方法
如果你有这个架构:
const schema = Joi.object({
first_name: Joi.string().label('First Name')
});
并且你验证了一个无效的对象:
const { error,value } = schema.validate({ first_name: 123 })
error.details 对象如下所示:
[
{
message: 'first_name must be a string',path: [ 'first_name' ],type: 'string.base',context: {
label: 'First Name',valids: 123,key: 'first_name'
}
}
]
但是,如果您使用 .label('First Name') 这就是您从错误对象中得到的:
[
{
message: 'First Name must be a string',<< overrides
path: [ 'first_name' ],<< overrides
valids: 123,key: 'first_name'
}
}
]
因此,.label 将覆盖 message 和 context.label。
根据 documentation,您不能传递任何其他参数。