Reputation: 533
Trying to validate a request, at certain times the request is made there may or may not be some objects provided on the request. How does one set the correct options to allow this to happen with out Joi throughing an error? i.e. {"statusCode":400,"error":"Bad Request","message":"child \"B\" fails because [\"B\" must be an object]"}
I seem to incorrectly be using the .optional() method. I set optional() on an object in the schema thinking that it will allow an object to be passed or not, but Joi seems to consider it an error if the object is not passed in the request
validate: {
payload: {
A: Joi.object().keys({
a1: Joi.string().allow('').optional(),
}).allow(null).optional(),
B: Joi.object().keys({
b1: Joi.string().allow('').optional(),
}).allow(null).optional(),
}
I expect the above allow me to pass in a payload like
{
A: { a1 : 'words' }
}
without returning an error about 'B', but this is not the case.
Upvotes: 0
Views: 966
Reputation: 533
Finding some other thread at
Joi validation set default as empty object
using .default({}) on the key will allow it to pass validation.
Upvotes: 1