35

I'm using Joi package for server side Validation.
I want to check if a given string is in a given list or if it is not in a given list.(define black list or white list for values)
sth like an "in" or "notIn" function. How can I do that?

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

4 Answers 4

45
+50

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 (-:

Sign up to request clarification or add additional context in comments.

2 Comments

in joi/hapi there is no option like valid or invalid :|
@BadriDerakhshan: If you're talking about @hapi/joi then there is no @hapi/joi anymore! that package got deprecated last month & Joi is officially back to Joi. (npmjs.com/package/@hapi/joi) (Also valid and invalid do exists in @hapi/joi)- which is kind of frustrating as users has to switch from Joi to @hapi/joi last year and in a year again back to Joi :-)
30

How about:

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

There are also aliases: .allow and .only

and .disallow and .not

1 Comment

This no longer works as 'valid' no longer accepts arguments of type array
2

This works in [2023]:

var schema = Joi.object({
    status: Joi.string().valid("pending", "in-review", "resolved")
});

Comments

0

Update from 10 Oct 2022 Now valid function requires Object

Joi.string().valid({ ...values_array }),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.