I have a form that uses a pattern to validate because some of the keys can be years that change and have any number.
An example of the JSON:
{
yearCosts: {
2022: {
other: 40
},
2023: {
other: 60
}
},
yearJustify: {
years: {
2022: {
otherSources: 'Why we need this money this year.'
},
2023: {
otherSources: 'Why we need this money this year.'
}
}
}
}
It is possible to have no costs for a year. If so, then one does not need to provide justification (and therefore no need for validation). However, if there is a cost, then there needs to be justification.
I have been able to get the following to be able to validate in the Joi Sandbox:
Joi.object({
costAllocation: Joi.object().pattern(
/\d{4}/,
Joi.object({
other: Joi.number().positive().allow(0).required().messages({
'number.base':
'Provide a number of hours greater than or equal to 0.',
'number.positive':
'Provide a number of hours greater than or equal to 0.',
'number.allow':
'Provide a number of hours greater than or equal to 0.',
'number.empty':
'Provide a number of hours greater than or equal to 0.',
'number.format': 'Provide a valid number of hours.'
})
})
),
costAllocationNarrative: Joi.object({
years: Joi.object({
2022: Joi.alternatives().conditional('....costAllocation.2022.other', {
is: Joi.number().greater(0),
then: Joi.object({
otherSources: Joi.string().trim().min(1).required().messages({
'string.base': 'Provide a description of other funding.',
'string.empty': 'Provide a description of other funding.',
'string.min': 'Provide a description of other funding.'
})
}),
otherwise: Joi.object({
otherSources: Joi.any()
})
}),
2023: Joi.alternatives().conditional('....costAllocation.2023.other', {
is: Joi.number().greater(0),
then: Joi.object({
otherSources: Joi.string().trim().min(1).required().messages({
'string.base': 'Provide a description of other funding.',
'string.empty': 'Provide a description of other funding.',
'string.min': 'Provide a description of other funding.'
})
}),
otherwise: Joi.object({
otherSources: Joi.any()
})
})
})
})
})
But I cannot seem to get the second half of the validation to follow a pattern that corresponds to the correct year above.