Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HapiJS/Joi Allow field to be String or Object with specific keys

Tags:

node.js

joi

I'm trying to validate a POST request where the title can be a String or an Object with language keys and values. Example:

{
    title: 'Chicken',
    ...
}
//OR
{
    title: {
        en_US: 'Chicken',
        de_DE: 'Hähnchen'
    }
    ...
}

And with Joi I'm trying to validate like so:

{
   title: Joi.any().when('title', {
        is: Joi.string(),
        then: Joi.string().required(),
        otherwise: Joi.object().keys({
            en_US: Joi.string().required(),
            lt_LT: Joi.string()
        }).required()
    }),
...
}

However, when I try to validate I get the error AssertionError [ERR_ASSERTION]: Item cannot come after itself: title(title) Is there a way to use when with the same field?

like image 371
Combustible Pizza Avatar asked May 24 '18 11:05

Combustible Pizza


1 Answers

Take a look at using .alternatives() rather than .when() for this situation. .when() is better used when the value of your key is dependant on another key's value within the same object. In your scenario, we've only got the one key to worry about.

A possible solution using .alternatives() could look like:

Joi.object().keys({
    title: Joi.alternatives(
        Joi.string(),
        Joi.object().keys({
            en_US: Joi.string().required(),
            lt_LT: Joi.string()
        })
    ).required()
})
like image 88
Ankh Avatar answered Oct 15 '22 09:10

Ankh