【问题标题】:Joi validation display custom error messageJoi 验证显示自定义错误信息
【发布时间】:2021-08-12 09:53:48
【问题描述】:

您好,我正在使用"@hapi/joi": "^15.1.1"。很遗憾,我现在无法更新到最新的 Joi 版本。

这是我的验证模式

 const schema = {
    name: Joi.string()
      .allow("")
      .max(30),
    addLine1: Joi.string()
      .required()
      .label("Address Line 1"),
    locality: Joi.string()
      .required()
      .label("City"),
    region: Joi.string()
      .required()
      .label("State"),
    zipCode: Joi.number()
      .required()
      .label("Zip Code"),
    phoneNo: Joi.string()
      .required("Required")
      .regex(/^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/)
      
  };

然后我验证并显示发生的第一个错误

const result = Joi.validate(this.state.addressDetails, this.schema, {
      abortEarly: true,
    });
 return const errors = result.error.details[0].message;

这行得通。唯一的问题是我想显示自定义错误消息而不是默认错误消息。

地址的默认错误消息是"Address Line 1" is not allowed to be empty" 而不是这个,我想显示"Address is required!"

对于正则表达式,默认一个是

phoneNo with value "555" fails to match the required pattern: /^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/

相反,我想显示please enter a valid phone number

如何使用版本15.1.1 实现这一点。 较新版本的 messages 在这里无济于事。

【问题讨论】:

    标签: javascript node.js reactjs vue.js joi


    【解决方案1】:

    尝试从 .error 回调中返回消息

      addLine1: Joi.string()
          .required()
          .label("Address Line 1").error(()=>'"Address Line 1" is not allowed to be empty'),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2020-09-13
      • 1970-01-01
      • 2018-02-08
      相关资源
      最近更新 更多