如何为Joi中的所有字段设置默认自定义消息



是否可以为所有字段设置默认的自定义错误消息?

将自定义错误设置为单个字段是相当重复的。这就是我所做的:

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;
}
});
});
});

您可以为错误定义一个自定义方法。

const customMessage = (fieldName, min) => {
return {
"string.base": fieldName + "should be a type of text",
"string.empty": fieldName + " cannot be an empty field",
"string.min": fieldName + " should have a minimum length of " + min,
"any.required": fieldName + " is a required field"
}
};
const email = Joi
.string()
.email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
.required()
.messages(customMessage("email",20));
const password = Joi
.string()
.min(8)
.max(50)
.required()
.messages(customMessage("password",10));

相关内容

  • 没有找到相关文章

最新更新