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.
Yes. Just add
.required()to all fields insideheadquarterand they will become required. Makingheadquarteroptional does not make any fields inside it optional. Optional status only makesundefinedvalid value for the field.https://joi.dev/api/?v=17.12.2#anyoptional