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?
Object schema validation. express-validator and joi can be primarily classified as "npm Packages" tools. express-validator and joi are both open source tools. It seems that joi with 17.7K GitHub stars and 1.41K forks on GitHub has more adoption than express-validator with 5.1K GitHub stars and 535 GitHub forks.
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()})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With