4

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

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I've always missed this ".every" thing. It works perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.