Search code examples
node.jsjoi

Removing special characters from @hapi/joi error messages


I'm using Joi from @hapi/joi to validate my data, but when I try to customize the error messages by removing the backward slashes and the double quotes; it doesn't work.

My validation function

const validateSignup = (user) => {

  const schema = Joi.object().keys({
    first_name: Joi.string().min(3).max(20)
      .required(),
    last_name: Joi.string().min(3).max(20)
      .required(),
    email: Joi.string().email({ minDomainSegments: 2 }).trim().required(),
    password: Joi.string().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/)
      .required()

  });

  const options = {
    abortEarly: false,
    key: '"{{key}}" ',
    escapeHtml: true,
    language: {
      string: {
          base: '{{key}} '
      }
  }
};
  return schema.validate(user, options);
};

I tried to search online but for some reason, it's not working. What am I doing wrong? Please, help.

Postman's response

Response body


Solution

  • Customizing error message in @hapi/joi to remove double quote is available after this release https://github.com/hapijs/joi/issues/2262. Default label:'"'. Though this feature is available, you may not get typings for it till https://www.npmjs.com/package/@types/hapi__joi/v/16.0.12, hope they will add soon.

        const options = {
          errors: {
            wrap: {
              label: ''
            }
          }
        };
    
        return schema.validate(user, options);
    

    In your case, the above configuration removes the double quote.

    Here is the output without double quote