Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
Yup validation of first and last element in array of objects

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),
                                        }),
                                    ),
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!