Ravi
Ravi

Reputation: 49

Is there a way to skip the yup validation to the last object in an array of objects?

I'm using formik for our form implementation. We have a requirement of appending a new row of fields when you are adding data in the above row. While submitting the form we're getting the yup validation error as the newly added row doesn't met the condition. Please suggest any solution to skip the validation for the newly added row(last row).

This is the validation schema    

    Yup.object().shape({
        key1: Yup.object({
          key2: Yup.object({
            key3: Yup
              .array()
              .of(Yup.object().shape({
                salary: Yup.object({
                  description: Yup.string().matches(/^([a-zA-Z0-9]+){0,50}$/, 'description is not valid'),
                }),
              })),`enter code here`
          }),
        }),
      });

Validation schema is applying for entire array of objects, which is expected behavior.

Upvotes: 3

Views: 7122

Answers (3)

Narender
Narender

Reputation: 1

  name: yup
.array()
.transform((field) => {
  if (field.length !== 1) {
    field = field.slice(0, -1);
  }
  return field;
})
.of(
  yup.object().shape({
    name: yup.string().required("name Code Required"),
  })
),

Upvotes: 0

Sanka Sanjeeva
Sanka Sanjeeva

Reputation: 3540

For me, this works

yup.object().shape({
  users: yup
    .array()
    .transform((field) => field.slice(0,-1))
    .of(
      yup.object().shape({
        email: yup
          .string()
          .email('Email is Invalid')
          .required('Email is required'),
      }),
    ),
}),

Upvotes: 1

Vencovsky
Vencovsky

Reputation: 31683

You can have two approaches.

1 - Make the row in a new field.

You can a field with all rows and another field with only the last row. This way you will need to use setFieldValue so when you add a new row, you get the last row field, push to the field with all rows, and then set the new last row.

This might do too much things, but you can have one benefit, wich is having a custom validation for the last item in the row (because it's in another field).

2 - Yup Custom validation

You can use .test to validate the array, you can loop through the array and ignore the last value.

You can also use a yup schema inside that function and use isValid or validate to check it, so you don't need to make the test by yourself.

Edit:

I just made an example where you have a list of strings and you validate if the lenght of the string is greater or equal 3.

It validates all items in the array, except for the last one.

Upvotes: 1

Related Questions