我需要使用 formik 或 yup 验证动态创建的字段。我在这里看到了 jquery validatioh 中完成的验证
我的代码在这里 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'),
})
),
Run Code Online (Sandbox Code Playgroud)
而你的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>
))
}}
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到完全准备好的代码
| 归档时间: |
|
| 查看次数: |
8569 次 |
| 最近记录: |