formik - 使用 Formik Yup 验证动态创建的字段
问题描述
我需要使用 formik 或 yup 验证动态创建的字段。我已经在 jquery validatioh here中看到了此验证
我的代码在这里 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>
))
}}
你可以在这里找到完全准备好的代码
推荐阅读
- android - 如何避免在数组中写入多个 id 的 textview
- r - 检索数据框的名称以用作列名称中的前缀
- python - 来自 google-cloud-sdk 的 Pylance 问题
- distance - 将两个距离函数合二为一进行相似度度量的内部工作
- reactjs - 如何让 axios 拦截器访问我的反应应用程序的状态?
- php - 在开发模式和生产模式之间切换不会在 symfony 4 项目的缓存文件夹中生成所有必需的文件
- javascript - 保持在同一页面上的路由 vuejs
- c++ - Boost - 子进程仍然是僵尸
- flutter - NoSuchMethodError:null 上的无效成员:'complaintType'
- google-analytics - Google Analytics:如何在用户访问注册页面但未注册离开时跟踪用户?