1

I am using Joi for my project server side validation.

I have an array which is populate from database for eg:

let s = ['a','b','c'];

Now I need to check if for a given field the values is within the array s only. like this:

Joi.object({
    value:  Joi.string().valid(...s).required()
});

I used Nodejs - Joi Check if string is in a given list as reference, but I keep getting this error:

TypeError: Joi.string(...).valid is not iterable (cannot read property Symbol(Symbol.iterator))

However, when the values are hardcoded, it works perfectly:

Joi.object({
   value:  Joi.string().valid('a','b','c').required()
});

Any idea how to solve this?

Tarounen
  • 1,119
  • 3
  • 14
  • 25

1 Answers1

0

You need to use the Array() constructor:

const s = new Array("1", "2", "3");

const schema = Joi.object({
    a: Joi.string().valid(...s).required()
})

schema.validate({ a: "1" }) // valid
schema.validate({ a: "555" }) // invalid

If you want to keep your variable a , you can do this:

const a = ["1", "2", "3"];
const s = new Array(...a);
soltex
  • 2,993
  • 1
  • 18
  • 29