Nodejs – Joi Check if string is in a given list

You are looking for the valid and invalid functions.
v16: https://hapi.dev/module/joi/api/?v=16.1.8#anyvalidvalues—aliases-equal
v17: https://hapi.dev/module/joi/api/?v=17.1.1#anyvalidvalues—aliases-equal

As of Joi v16 valid and invalid no longer accepts arrays, they take a variable number of arguments.

Your code becomes

var schema = Joi.object().keys({
    firstname: Joi.string().valid(...['a','b']),
    lastname: Joi.string().invalid(...['c','d']),
});

Can also just pass in as .valid('a', 'b') if not getting the values from an array (-:

Leave a Comment