How to set custom message for regex in joi

Viewed 5892

When I validate my graphql arguments, I'm getting error message like this for the password field.

"password" with value "" fails to match the required pattern: /^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/"

I don't want to show regex pattern in the error message. So I tried to set the custom error message for the password field but still it's showing the regex pattern.

import Joi from "joi";

export default Joi.object().keys({
  email: Joi.string().email().required().label("Email"),
  username: Joi.string().alphanum().min(4).max(20).required().label("Username"),
  name: Joi.string().min(4).max(256).required().label("Name"),
  password: Joi.string()
    .min(8)
    .regex(/^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/)
    .required()
    .label("Password")
    .messages({
      "string.min": "Must have at least 8 characters",
      "object.regex": "Must have at least 8 characters",
    }),
});

I think it's not selecting the regex by object.regex. Please help.

1 Answers

To know what error is being thrown, you can debug the error object (by logging it), and then finding the type of error.

Example:

const Joi = require('@hapi/joi');

const joiSchema = Joi.object().keys({
  password: Joi.string()
    .min(8)
    .regex(/^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/)
    .required()
    .label("Password")
    .messages({
      "string.min": "Must have at least 8 characters",
      "object.regex": "Must have at least 8 characters",
      "string.pattern.base": "enter your custom error here..."
    })
});

const validationResult = joiSchema.validate({ password: "2" }, { abortEarly: false });
console.log(validationResult.error.details.map(errDetail => errDetail.type), validationResult.error);

This outputs ["string.min", "string.pattern.base"]. details has 2 errors because of string.min and string.pattern.base, and abortEarly is set to false.

Related