Tengo un formulario que usa un patrón para validar porque algunas de las claves pueden ser años que cambian y tienen cualquier número.
Un ejemplo del 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.' } } } }Es posible no tener gastos durante un año. Si es así, entonces no es necesario proporcionar una justificación (y, por lo tanto, no es necesario validar). Sin embargo, si hay un costo, entonces debe haber una justificación.
He podido conseguir lo siguiente para poder validar en el Sandbox de Joi :
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() }) }) }) }) })Pero parece que no puedo lograr que la segunda mitad de la validación siga un patrón que corresponda al año correcto anterior.