Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi validation of array

Tags:

hapijs

joi

trying to validate that an array has zero or more strings in one case and that it has zero or more objects in another , struggling with Joi docs :(

validate: {         headers: Joi.object({                 'content-type': "application/vnd.api+json",                 accept: "application/vnd.api+json"         }).options({ allowUnknown: true }),         payload : Joi.object().keys({             data : Joi.object().keys({                 type: Joi.any().allow('BY_TEMPLATE').required(),                 attributes: Joi.object({                     to : Joi.string().email().required(),                     templateId : Joi.string().required(),                     categories : Joi.array().items( //trying to validate here that each element is a string),                     variables : Joi.array({                         //also trying to validate here that each element is an Object with one key and value                     })                 })             }).required()         })     } 
like image 391
1977 Avatar asked Mar 07 '17 19:03

1977


People also ask

How do you validate an array of strings?

To validate is either string or array of strings with Yup, React and JavaScript, we can use the mixed and when methods. to add a form with the Formik and Form components. We set the validationSchema prop to an object returned by object and shape to let us validate the value object.

What is Joi object?

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

Joi.array().items() accepts another Joi schema to use against the array elements. So an array of strings is this easy:

Joi.array().items(Joi.string()) 

Same for an array of objects; just pass an object schema to items():

Joi.array().items(Joi.object({     // Object schema })) 
like image 51
cdhowie Avatar answered Sep 27 '22 19:09

cdhowie