margherita pizza
margherita pizza

Reputation: 7145

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.

Upvotes: 3

Views: 6647

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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'),

Upvotes: 2

Related Questions