arb / celebrate

A joi validation middleware for Express.
MIT License
1.34k stars 65 forks source link

Validate array in query parameters? #154

Closed vedantroy closed 4 years ago

vedantroy commented 4 years ago

If we have an array in the query parameters, how do we validate it?

arb commented 4 years ago

Assuming the items in your query string are objects... you would use something like

[Segments.QUERY]: Joi.array().items(Joi.object(.....))

Check here for a more complete example. Per the README here, I'm not able to give help writing Joi validation schemas, but there are plenty of other resources to help you do so.

Any of those options would give you a much more specific help on writing Joi schemas. If you have any additional questions about celebrate specifically, please feel free to open a new issue.

vedantroy commented 4 years ago

I tried using Joi.array(), but it only recognized the array as a string. Joi.number, Joi.string, and Joi.boolean all work fine.

arb commented 4 years ago

Then the way your Express server is parsing the query string doesn't result in an array OR the request you're making isn't passing values correctly as an array in the query string. Make sure req.query is the array you think it should be before worrying about validating it.

vedantroy commented 4 years ago

Thanks for the help so far. To clarify, an array is one of the query parameters in the query string (the actual string looks like this: ?parameter1=[value1,value2]&parameter2=someBoolean&parameter3=someNumber) . Also, every parameter in the query string/Segments.QUERY is, by default, a string, the only reason Joi.number and Joi.boolean work is because they accept strings. Is there some sort of middleware I have to plug in to parse the values in the query string into actual JS values?

arb commented 4 years ago

https://expressjs.com/en/resources/middleware/body-parser.html