【问题标题】:How to set default custom messages for all fields in Joi如何为 Joi 中的所有字段设置默认自定义消息
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2021-07-10
      • 2019-02-14
      相关资源
      最近更新 更多