joi validation: Set minimum array length conditionally

user2468170 picture user2468170 · Sep 9, 2014 · Viewed 9.4k times · Source

I have an array field which i would like to ensure that it has at least one element when a condition is met:

genre:Joi.array().includes(data.genres).when('field'{is:'fieldValue',then:Joi.required()})

If i changed the 'then' field with Joi.required().min(1), it complains.

Can i do this with Joi?

Answer

Gergo Erdosi picture Gergo Erdosi · Sep 9, 2014

You didn't mention what the error message was, but testing your code I suppose you got:

TypeError: Object [object Object] has no method 'min'

This error occurs because min() is a function of the array type. In the then: part you create a new validation object and Joi doesn't know you expect an array there. So you need to specify it:

then: Joi.array().min(1).required()

The full validation code is:

genre: Joi.array().includes(data.genres).when('field', {is: 'fieldValue', then: Joi.array().min(1).required()})