Joi validation of array

1977 picture 1977 · Mar 7, 2017 · Viewed 76.3k times · Source

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()
        })
    }

Answer

cdhowie picture cdhowie · Mar 7, 2017

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
}))