Reputation: 13
In Joi is there any way to validate elements of an array based on its index? I have this:
const schema = Joi.array().items(
Joi.object({
a: Joi.string(),
b: Joi.number()
})
)
and i want "a" required only for first element.
Upvotes: 1
Views: 1712
Reputation: 3531
Yes, there is a way. You can combine array.ordered with array.items:
const schema = Joi.array()
.ordered(Joi.object({
a: Joi.string().required(),
b: Joi.number()
}))
.items(Joi.object({
a: Joi.string(),
b: Joi.number()
}));
This way, the array must have the first item as the object you defined with a required, and the subsequent items wouldn't have the a required.
This validation will pass:
schema.validate([{ a: '123', b: 10 }, { a: '123', b: 10 }])
And this one will fail:
// ValidationError: "[0].a" is required
schema.validate([{ b: 10 }, { a: '123', b: 10 }])
It could be a little bit tricky if you want to validate some other element than the first one.
Upvotes: 1