Allow only specific values for key in Joi schema

mardok picture mardok · Feb 27, 2018 · Viewed 32.9k times · Source

Is there any other way to set specific values in Joi validation schema for key except regex pattern?

My example schema:

const schema = joi.object().keys({
    query: joi.object().keys({
        // allow only apple and banana
        id: joi.string().regex(/^(apple|banana)$/).required(),
    }).required(),
})

Answer

Jiby Jose picture Jiby Jose · Feb 27, 2018

You can also use valid like

const schema = joi.object().keys({
  query: joi.object().keys({
    // allow only apple and banana
    id: joi.string().valid('apple','banana').required(),
  }).required(),
})

Reference: https://github.com/hapijs/joi/blob/v13.1.2/API.md#anyvalidvalue---aliases-only-equal