Joi validation of array
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
}))
You can also try this way, I have been using it for long time and working fine for me.
If your array is array of objects than use below:
const Joi = require('joi');
let schema = Joi.object().keys({
items: Joi.array().items(
Joi.object({
item_id: Joi.number().required(),
item_qty: Joi.number().required(),
item_type_id: Joi.number().required(),
item_qty: Joi.number().required(),
base_price: Joi.number().required(),
actual_price: Joi.number().required(),
})
).required(),
});
let errors = Joi.validate(req.body, schema);
if you array is simple array than:
let schema = Joi.object().keys({
items: Joi.array().items(
Joi.number().required()
).min(10).required()});
you can try this:
function(data) {
const Schema = {
categories: Joi.array().items(Joi.string()),
variables: Joi.array().items(Joi.object().keys().min(1))
}
return Joi.validate(data, Schema)
}
for more details checkout this repo: https://github.com/raysk4ever/nodejs_withMongoRefArray
If you want to validate an array of strings in Joi:
Joi.array().items(Joi.string().valid("item1", "item2", "item3", "item4"))