Max*_*Max 12 reactjs yup react-hook-form
是否可以仅在字段存在时验证该字段?
我将创建一个应用程序。字段(电子邮件)可能会/可能不会显示在步骤 2 中,这取决于步骤 1 的选择选项。问题是我不能 put email: Yup.string().Required(),它会导致验证一直运行,即使该字段没有显示。
您可以设置一个附加的布尔键,其中值默认为 false。当您在步骤 1 中修改值时,将其更改为 true。然后,如果该键的值为 true,则应用验证。
像这样的东西。
const initialSchema= {
name: '',
isEmail: false, // change this when you want to add validation
email: '',
phone: '',
};
const validationSchema = Yup.object().shape({
name: Yup.string()
.required('Enter Name')
isEmail: Yup.boolean(),
email: Yup.string().when('isEmail', {
is: true,
then: Yup.string()
.required('Enter Email ID'),
otherwise: Yup.string(),
}),
phone: Yup.string()
.required('Enter Mobile No'),
});
Run Code Online (Sandbox Code Playgroud)
这是相同的文档参考。
更新:
这是工作代码和框。我添加了复选框display:none;,并在数据上下文中添加了默认状态值。
我在这里看到了另一个相关答案,也许这也是一个有效的解决方案?
https://github.com/jquense/yup/issues/1114
从那里复制代码:
const schema = yup.object({
phone: yup.string().when('$exist', {
is: exist => exist,
then: yup.string().required(),
otherwise: yup.string()
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30298 次 |
| 最近记录: |