Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

287
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda