[英]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.我在 formik 中使用并根据用户输入渲染多个 forms。
<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验证模式.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.它工作得很好,因为每个渲染的输入都在验证 email,但现在我有一个新的添加。 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).
我希望对象内的所有 email 都是唯一的,所以假设是否有 3 个 forms 所有不同的 forms 应该有不同的电子邮件(名称可以相同)。 So, how can i add this feature to my validation schema as the normal test function wont perfectly here
那么,我如何将此功能添加到我的验证模式中,因为正常测试 function 在这里不会完美
Thanks !谢谢 !
You can add a custom unique method to your yup schema and use it like this:您可以将自定义唯一方法添加到您的 yup 架构并像这样使用它:
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)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.