【发布时间】:2021-01-02 18:14:08
【问题描述】:
是否可以为所有字段设置默认的自定义错误消息?
为单个字段设置自定义错误是相当重复的。 我就是这样做的:
const email = Joi
.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
.required()
.messages({
'string.base': `"email" should be a type of 'text'`,
'string.empty': `"email" cannot be an empty field`,
'string.min': `"email" should have a minimum length of {#limit}`,
'any.required': `"email" is a required field`
});
const password = Joi
.string()
.min(8)
.max(50)
.required()
.messages({
'string.base': `"password" should be a type of 'text'`,
'string.empty': `"password" cannot be an empty field`,
'string.min': `"password" should have a minimum length of {#limit}`,
'any.required': `"password" is a required field`
});
我在Joi 文档中看到有一个defaults() 设置默认值的方法,我想知道它是否适用于设置默认自定义消息。
我希望它可以是这样的:
为字段设置默认自定义错误的示例
const customJoi = Joi.defaults(function (schema) {
return schema.error((errors) => {
return errors.map((error) => {
switch (error.type) {
case "string.min":
return { message: '{#field} exceeded maximum length of {#limit}' };
case "string.max":
return { message: '{#field} should have a minimum length of {#limit}' };
case "any.empty":
return { message: '{#field} cannot be an empty field.' };
case "any.required":
return { message: '{#field} is a required field.' };
default:
return error;
}
});
});
});
【问题讨论】:
标签: node.js express validation joi