hapi

Hapi/Joi Cannot apply rules to empty ruleset or the last rule added does not support rule properties


I am trying to display a custom message when users didn't put a password during login. This worked fine when I don't have a custom message for the password:

const ValidationSchemas = Joi.object({
  name: Joi.string().min(6).required().messages({
      "string.empty":"Display name cannot be empty",
      "string.min":"Min 6 characteers"
  }).optional(),
  email: Joi.string().min(6).required().email().message("Must be a valid email address"),
  password:Joi.string().min(6).required()
})

But the moment I tried to have a custom message for the empty password field, I got an error stating - Cannot apply rules to empty ruleset or the last rule added does not support rule properties

Here is the code that I am trying to have a custom message for the password:

const ValidationSchemas = Joi.object({
  name: Joi.string().min(6).required().messages({
      "string.empty":"Display name cannot be empty",
      "string.min":"Min 6 characteers"
  }).optional(),
  email: Joi.string().min(6).required().email().message("Must be a valid email address"),
  password:Joi.string().min(6).required().message("Password is required!")
})

How do I have a custom message for the password? many thanks in advance and greatly appreciate any help. thanks


Solution

  • Try the below example in your code:

    const ValidationSchemas = Joi.object({    
        name: Joi.string()  
          .min(6)
          .required()
          .messages({
            'string.empty': 'Display name cannot be empty',
            'string.min': 'Min 6 characters',
          })
          .optional(),
        email: Joi.string().min(6).required().email().message('Must be a valid email address'),
        password: Joi.string().required().min(6).message('Password is required!'),
      });