Hello,
based on 'hapi/examples/validation' I try to set up validation of an optional query parameter that shall be allowed to take on one or more of a set of defined values, similar to an "enum" type. However, trying the following configuration and requests result in a an error saying {"code":400,"error":"Bad Request","message":"the value of state must be an Array". Same thing goes for using 'state: hapi.types.Array()' only. Any clue?
Configuration:
...
validate: {
path: {
id: hapi.types.String().required()
},
query: {
color: hapi.types.Array().includes(hapi.types.String().valid('red'
, 'blue', 'yellow'))
}
}
...
Test requests:
curl --request GET http://localhost:8080/test/5251c?color=red
curl --request GET http://localhost:8080/test/5251c?color=red&color=blue
Typos in my problem description above, please treat 'state' as synonymous with 'color'.
color: hapi.types.String().valid('red', 'blue', 'yellow')
Thanks for the prompt answer. Your suggestion seems to work fine for handling 0 to one value, but in my case I would like to allow 0 to many values of "color". Looking at 'hapi/examples/validation', I see that using an array type in the validation rule suggests a solution to my case (see definition of /config route and the suggested two /config URLs to try at the bottom of the file) but I cannot get it to work. Using String works fine for 0 or one value but passing two values or more in the query gives an error message saying that the value must be of type String. And vice versa, using Array works for 0, two or more values but passing one value in the query gives an error message saying that the value must be of type Array. Should Array work in this case, or is another construct needed?
Array should work. If it doesn't, open an issue in https://github.com/spumko/joi as that's the internal implementation.
For newer versions of hapi, the way to go is: Joi.string().allow('red', 'blue', 'yellow').
Just to add to what you wrote, @joscha. Based on the docs: "Note that this whitelist of allowed values is _in addition_ to any other permitted values. To create an exclusive whitelist of values, see any.valid(value)."
For an _exclusive whitelist_, Joi.string().valid('red', 'blue', 'yellow') should still be the way.
For anyone who needs to load an array, valid requires the this context to be set to the joi object.
This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.
Most helpful comment
Just to add to what you wrote, @joscha. Based on the docs: "Note that this whitelist of allowed values is _in addition_ to any other permitted values. To create an exclusive whitelist of values, see any.valid(value)."
For an _exclusive whitelist_,
Joi.string().valid('red', 'blue', 'yellow')should still be the way.