首页 > 解决方案 > 如何为 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;
            }
        });
    });
});

标签: node.jsexpressvalidationjoi

解决方案


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

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

推荐阅读