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

Shifut Hossain picture Shifut Hossain · Oct 16, 2019 · Viewed 13.5k times · Source

I've created following Schema for validation using Joi:

const createProfileSchema = Joi.object().keys({
  username: Joi.string()
    .required()
    .message("username is required")
    .empty()
    .message("username is not allowed to be empty")
    .min(5)
    .message("username must be greater than 5 characters")
    .max(20)
    .message("username must be less than 5 characters")
});

But it throws the flowing error:

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

      4 |   username: Joi.string()
      5 |     .required()
    > 6 |     .message("username is required")
        |      ^
      7 |     .empty()
      8 |     .message("username is not allowed to be empty")
      9 |     .min(5)

Actually I want to set a custom message for every individual error case.

Answer

SuleymanSah picture SuleymanSah · Oct 16, 2019

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