Home > database >  Yup validation of first and last element in array of objects
Yup validation of first and last element in array of objects

Time:11-01

I have a field in my form(Formik) which contains and array of objects with two timestamps in each one. My validation schema now works for all elements of array, but the goal is to check only first and last object in array, all other object can be empty. The length of the array changes dynamically. How can I do that?

"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"
}]

This works only when all objects filled with timestamps:

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),
                                        }),
                                    ),

CodePudding user response:

I don't know of any way you can use shape() to do what you want, but you can use a test function instead:

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;
              }
            )
        })
    })
)}

  • Related