0

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.

ndyr
  • 503
  • 4
  • 20

1 Answers1

1

Finding some other thread at

Joi validation set default as empty object

using .default({}) on the key will allow it to pass validation.

ndyr
  • 503
  • 4
  • 20
  • Are you sure that your payload has only the key 'A'? I tested out your schema with your payload example, and it works, with no errors. By using default({}) you are forcing your payload to always have a key 'B' with an empty object. – soltex Jul 16 '19 at 11:52