简体   繁体   中英

Joi validation display custom error message

Hi I am using "@hapi/joi": "^15.1.1" . Unfortunately, I can't update to the latest Joi version right now.

This is my validation schema

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

Then I validate and display the first error that occurred

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

This works. The only problem is I want to display a custom error message instead of the default one.

Default error message for address is "Address Line 1" is not allowed to be empty" Instead of this, I want to display "Address is required!"

For the regex default one is

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

Instead, I want to display please enter a valid phone number

How could I achieve this with version 15.1.1 . Newer versions messages thing won't help here.

Try out to return the message from the.error callback

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM