Search code examples
node.jstypescriptjoi

Joi custom .or() message


I'm trying to customize an .or() function message on Joi, like this:

Joi schema

The Joi default message is this one:

Validation Error: "value" must contain at least one of [optionOne, optionTwo]

I want it to be like this:

Please, select one of the options

I tried using .message and .messages functions and also .error, but these don't work for me.

Are there another options to customize an .or() error message?


Solution

  • Using .messages() is the right way to go, but the trick is finding the relevant message key. We can have a look in Joi's list of errors for something that matches.

    The one we're after is object.missing.

    The OR or XOR condition between the properties you specified was not satisfied in that object, none of them were set.

    Therefore your schema could look something like this:

    Joi.object().keys({
        a: Joi.string(),
        b: Joi.string()
    })
        .or('a', 'b')
        .messages({
            'object.missing': 'Please, select one of the options'
        })