Reputation: 109
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 !
Upvotes: 0
Views: 577
Reputation: 6915
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)
});
Upvotes: 1