Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only specific values for key in Joi schema

Tags:

javascript

joi

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(),
})
like image 346
mardok Avatar asked Feb 27 '18 11:02

mardok


3 Answers

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

like image 174
Jiby Jose Avatar answered Nov 14 '22 12:11

Jiby Jose


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

like image 33
anli Avatar answered Nov 14 '22 13:11

anli


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.

like image 2
Rahul Avatar answered Nov 14 '22 13:11

Rahul