简体   繁体   中英

Validation of specific key inside formik's "FieldArray" array of objects with yup

I am using in formik and rendering multiple forms based on the user input.

<FormikProvider value={formik}>
<form onSubmit={formik.handleSubmit}>
<FieldArray name="employeeInfo">
            <>
              {formik.values.employeeInfo.length > 0 &&
                formik.values.employeeInfo.map(
                  (employeeInfo: any, index: any) => (
                    <div className="person-panel" key={index}>


                         <PlainInput
                         {...all the other props }
                          name={`employeeInfo.${index}.name`}
                          question="Name"
                        />

                        <PlainInput
                         {...all the other props }
                          name={`employeeInfo.${index}.email`}
                          question="Email"
                        />
                    </div>
                  )
                )}
            </>
          </FieldArray>
          </form>
          </FormikProvider>

The issue I am facing is as of now my validationschema looks like

validationschema.js

export const validationSchemaLifeSummarySecond = Yup.object().shape({
  employeeInfo: Yup.array().of(
    Yup.object().shape({
     name: Yup.string()
    .typeError("Preencha este campo")
    .required("Preencha este campo"),

      email: Yup.string()
        .required("Este campo é obrigatório")
        .email("Formato de e-mail incorreto")
        .typeError("Formato de e-mail incorreto"),
    })
  ),
});

which works perfectly fine as every input rendered is validating the email, but now I have a new addition in it. I want all the email inside the objects to be unique, so lets say if there are 3 forms all different forms should have different emails (the names can be same). So, how can i add this feature to my validation schema as the normal test function wont perfectly here

Thanks !

You can add a custom unique method to your yup schema and use it like this:

Yup.addMethod(Yup.array, "unique", function (message, mapper = (a) => a) {
  return this.test("unique", message, function (list) {
    return list.length === new Set(list.map(mapper)).size;
  });
});

const validationSchemaLifeSummarySecond = Yup.object().shape({
  employeeInfo: Yup.array()
    .of(
      Yup.object().shape({
        name: Yup.string()
          .typeError("Preencha este campo")
          .required("Preencha este campo"),

        email: Yup.string()
          .required("Este campo é obrigatório")
          .email("Formato de e-mail incorreto")
          .typeError("Formato de e-mail incorreto")
      })
    )
    .unique("duplicate email", (a) => a.email)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM