hapi.jsjoi

Can we make a Joi object optional but the fields nested inside required if the object is invoked?


export const OrganizationUpdateSchema = Joi.object({
      uid: Joi.string().trim().required(),
      organizationDetails: Joi.object({
             email: Joi.string().email().trim(),
              organizationName: Joi.string().trim(),
              headquarter: Joi.object({
                      id: Joi.string().trim(),
                      name: Joi.string().trim(),
                      address: Joi.string().trim(),
                       state: Joi.string().trim(),
                       street: Joi.string().trim(),
                      pincode: Joi.string().trim().length(6),
       })
})

In the above code, I want to make headquarter optional. However if headquarter is in fact filled in the request body, the fields inside (id, name, address, state, street and pincode) should all be made mandatory.

The confusing part is whether Joi will throw an error if the nested field are not in fact used because the whole object is optional.


Solution

  • Yes. Just add .required() to all fields inside headquarter and they will become required. Making headquarter optional does not make any fields inside it optional. Optional status only makes undefined valid value for the field.

    Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.

    https://joi.dev/api/?v=17.12.2#anyoptional