簡體   English   中英

Joi 驗證顯示自定義錯誤信息

[英]Joi validation display custom error message

嗨,我正在使用"@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在這里無濟於事。

嘗試從.error回調中返回消息

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM