I am having trouble with a Joi validation schema where the validation logic needs to handle different version ranges dynamically. The version ranges for legacy and current reports are defined in a configuration object, and I need the validation to adapt based on these ranges.
The validation schema does not seem to work correctly even though isLegacyReport and isCurrentReport functions return appropriate boolean values. I suspect there might be an issue with how these functions are integrated into the Joi when conditions.
export const reportValidator = {
params: Joi.object({
version: Joi.string()
.required()
.pattern(/^v[1-9]d*$/)
}),
body: Joi.object({
end_date: Joi.date().required(),
start_date: Joi.date().required(),
org_id: Joi.number().when(Joi.ref('/params.version'), {
is: Joi.string().custom((value) => isCurrentReport(value)),
then: Joi.required(),
otherwise: Joi.forbidden()
}),
state_id: Joi.number().when(Joi.ref('/params.version'), {
is: Joi.string().custom((value) => isCurrentReport(value)),
then: Joi.required(),
otherwise: Joi.forbidden()
}),
zone_id: Joi.array().items(Joi.number().required()).when(Joi.ref('/params.version'), {
is: Joi.string().custom((value) => isCurrentReport(value)),
then: Joi.required(),
otherwise: Joi.forbidden()
}),
office_id: Joi.array()
.items(Joi.number().required())
.when(Joi.ref('/params.version'), {
is: Joi.string().custom((value) => isLegacyReport(value)),
then: Joi.required(),
otherwise: Joi.forbidden()
})
})
};