85

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(),
})
Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64
mardok
  • 2,135
  • 2
  • 23
  • 37

3 Answers3

146

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

Jiby Jose
  • 3,745
  • 4
  • 24
  • 32
  • 3
    it is allowing only one among two, How can we make it for both. – Vinod Kumar Marupu Sep 06 '18 at 15:52
  • how can I prevent price key in payload price: Joi.when('pricing', { is: 'FIXED', then: //prevent adding price here, otherwise: Joi.number() .min(1) .max(1000) .required() }) – tarek noaman Apr 03 '20 at 13:35
  • @tareknoaman First off, that sounds pretty unrelated to this question. But you might be able to omit the 'then'. If that doesn't work, make a new question. – Andy Apr 30 '20 at 12:55
  • @VinodKumarMarupu Your comment makes no sense. A string can only be one value at time. You would probably use an array or an additional key to allow more values. – Andreas Bergström Jan 18 '21 at 13:46
7

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.

Rahul
  • 71
  • 1
  • 2
1

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

anli
  • 515
  • 6
  • 9