Allow only specific values for key in Joi schema

JavascriptJoi

Javascript Problem Overview


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(),
})

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

If you want to accept one or more values (apple, banana or both) you can use allow: https://joi.dev/api/?v=17.3.0#anyallowvalues

Solution 3 - Javascript

You can try with .valid() to allow joi only with that specific string .

const schema = joi.object().keys({
  query: joi.object().keys({
    role: joi.string().valid('admin','student').required(), // joi would allow only if role is admin or student.
  }).required(),
})

This is absolutely equal to giving "enam" field in mongoose ODM for representing objects in mongodb.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmardokView Question on Stackoverflow
Solution 1 - JavascriptJiby JoseView Answer on Stackoverflow
Solution 2 - JavascriptanliView Answer on Stackoverflow
Solution 3 - JavascriptRahulView Answer on Stackoverflow