How to set custom error messages in @hapi/joi?

You can try this

const Joi = require("@hapi/joi"); // as of v16.1.8

const createProfileSchema = Joi.object().keys({
  username: Joi.string()
    .required()
    .empty()
    .min(5)
    .max(20)
    .error(errors=>{ 
     errors.forEach(err=>{  
     switch(err.code){
         case "string.empty":
         err.message='Please insert username'
         break

         case "string.max":
         err.message='username is not allowed to be empty'
         break
        }
      })
    return errors
});

You can try something like this with latest version of @hapi/joi package.

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

const createProfileSchema = Joi.object().keys({
  username: Joi.string()
    .required()
    .empty()
    .min(5)
    .max(20)
    .messages({
      "string.base": `"username" should be a type of 'text'`,
      "string.empty": `"username" cannot be an empty field`,
      "string.min": `"username" should have a minimum length of {#limit}`,
      "string.max": `"username" should have a maximum length of {#limit}`,
      "any.required": `"username" is a required field`
    })
});

const validationResult = createProfileSchema.validate(
  { username: "" },
  { abortEarly: false }
);

console.log(validationResult.error);

Detailed info can be found in docs:

https://github.com/hapijs/joi/blob/master/API.md#list-of-errors