Search code examples
javascriptnode.jsjoi

How create a custom message for method valid () in JOI library?


I am validating the property subscription like this:

Joi.object({
  subscription: Joi.string()
    .valid('starter', 'pro', 'business')
    .required()
    .messages({
      'string.base': `{{#label}} should be a type of string`,
      'string.empty': `{{#label}} must contain value`,
      'any.required': `missing field {{#label}}`,
    }),
})

If subscription not one of these 'starter', 'pro', 'business', I have a message

""subscription" must be one of [starter, pro, business]"

So, how create a custom message for method valid () in JOI library?


Solution

  • You can use any.only:

    Only some values were allowed, the input didn't match any of them.

    Like this:

    'any.only': `missing field {{#label}}`
    

    This will output the following custom error message:

    Validation Error: missing field "subscription"