Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate array contains specific value using joi

Tags:

javascript

joi

I'm looking for a way to validate that an array contains a required value using joi.
Found these issues online - #1, #2, but none of them has a definitive answer.
I tried several stuff but they doesn't seem to work, like:
joi.array().items(joi.string().allow('required-string').required()), joi.array().items(joi.string().label('required-string').required()), joi.array().items(joi.string().valid('required-string'))

This is what I'm trying to achieve:

Accepted:

['required-string'], ['required-string', 'other'], ['other','required-string'], ['other',...,'required-string',....,'more-other']

Denied:

[], ['other'], [null], etc..
like image 865
nirsky Avatar asked Aug 07 '17 07:08

nirsky


People also ask

What is Joi validator?

Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.


1 Answers

You can use array.items by listing all allowed types. If a given type is .required() then there must be a matching item in the array: joi API reference

joi.array().items(joi.string().valid('required-string').required(), joi.string())
like image 68
Carsten Avatar answered Oct 17 '22 08:10

Carsten