Reputation: 13290
I would like to accept an array of strings as an argument with Joi but when I pass only one item I receive the error value must be an array
. If I try to pass a second value that's empty to force array syntax conversion in Express I receive must be one of...
error after defining the strict set of possible values as empty is not strictly allowed.
Request schema:
const requestSchema = Joi.object().keys({
query: Joi.object().keys({
endTime: Joi.string().required(),
fields: Joi.array().items(
Joi.string().valid(
"value1",
"value2",
"value3"
)
),
startTime: Joi.string().required()
})
});
Upvotes: 2
Views: 4269
Reputation: 13290
The key here is the single()
function. Implementing this will allow you to pass a single value for an array and Joi will wrap the single value in an array so that it validates correctly:
const requestSchema = Joi.object().keys({
query: Joi.object().keys({
endTime: Joi.string().required(),
fields: Joi.array().items(
Joi.string().valid(
"value1",
"value2",
"value3"
)
).single(),
startTime: Joi.string().required()
})
});
This allows you to send fields=value1
which gets converted to: fields: ["value1"]
.
Upvotes: 2