Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

joi validation: Set minimum array length conditionally

Tags:

node.js

hapijs

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?

like image 320
user2468170 Avatar asked Sep 09 '14 08:09

user2468170


People also ask

Which is better express validator or 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.


1 Answers

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()})
like image 69
Gergo Erdosi Avatar answered Sep 25 '22 05:09

Gergo Erdosi