Tengo un campo en mi formulario (Formik) que contiene una matriz de objetos con dos marcas de tiempo en cada uno. Mi esquema de validación ahora funciona para todos los elementos de la matriz, pero el objetivo es verificar solo el primer y el último objeto de la matriz, todos los demás objetos pueden estar vacíos. La longitud de la matriz cambia dinámicamente. ¿Cómo puedo hacer eso?
"timeslots": [ { "startTime": "2021-10-31T22:30:00.000Z", "endTime": "2021-11-01T00:30:00.000Z" }, { "startTime": "", "endTime": "" }, { "startTime": "2021-11-02T22:30:00.000Z", "endTime": "2021-11-03T00:00:00.000Z" }]Esto funciona solo cuando todos los objetos están llenos de marcas de tiempo:
validationSchema={() => Yup.lazy(({ timeslots }) => ? Yup.object({ timeslots: timeslots.length > 0 && Yup.array().of( Yup.object().shape({ startTime: Yup.string().required(INVALID_FORM_MESSAGE.requiredField), endTime: Yup.string().required(INVALID_FORM_MESSAGE.requiredField), }), ),No conozco ninguna forma en que pueda usar shape() para hacer lo que quiera, pero puede usar una función de prueba en su lugar:
validationSchema={ Yup.lazy(({ timeslots }) => Yup.object({ timeslots: Yup.array() .of( Yup.object().shape({ startTime: Yup.string(), endTime: Yup.string() }) ) .test({ name: 'first-and-last', message: INVALID_FORM_MESSAGE.requiredField, test: val => val.every( ({ startTime, endTime }, index) => { if (index === 0 || index === val.length - 1) { return !!startTime && !!endTime; } return true; } ) }) }) )}