gpt4 book ai didi

formik - 使用 Formik Yup 验证动态创建的字段

转载 作者:行者123 更新时间:2023-12-04 14:15:03 37 4
gpt4 key购买 nike

我需要用 formik 或 yup 来验证动态创建的字段。我已经在 jquery validatioh here 中看到了这个验证。

like this对此to this

我的代码在这里 https://codesandbox.io/s/hidden-haze-47k73?file=/src/demo.js

我如何使用 formik 和 yup 实现这一点

最佳答案

如果您使用 formik FieldArray。您可以使用 yup 检查它的字段:

firends: Yup.array().of(
Yup.object().shape({
name: Yup.string().required('Name is required'),
email: Yup.string()
.email("Invalid email")
.required('Email is required'),
})
),

你的 FieldArray 将是:

<FieldArray                                                          
name="firends"
render={(arrayHelpers) => {
{values.firends && values.firends.length > 0 ? (
values.firends.map((friend, index) => (
<div key={index}>
<Field
className="form-control"
name={`friends.${index}.name`}
placeholder="name"
type="text"
/>
{errors &&
errors.friends &&
errors.friends[index] &&
errors.friends[index].name &&
(touched &&
touched.friends &&
touched.friends[index] &&
touched.friends[index].name) && (
<div className="field-error">
{errors.friends[index].name}
</div>
)}
<Field
className="form-control"
name={`friends.${index}.email`}
placeholder="email"
type="text"
/>
{errors &&
errors.friends &&
errors.friends[index] &&
errors.friends[index].email &&
(touched &&
touched.friends &&
touched.friends[index] &&
touched.friends[index].email) && (
<div className="field-error">
{errors.friends[index].email}
</div>
)}
</div>
))
}}

您可以找到完全准备好的代码 here

关于formik - 使用 Formik Yup 验证动态创建的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61114742/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com