【发布时间】:2021-04-13 06:00:30
【问题描述】:
是否可以仅在字段存在时对其进行验证?
我要创建一个应用程序。字段(电子邮件)可能/可能不会显示在第 2 步,这取决于第 1 步选择的选项。问题是我不能输入email: Yup.string().Required(),这会导致验证一直运行,即使字段不显示。
【问题讨论】:
标签: reactjs yup react-hook-form
是否可以仅在字段存在时对其进行验证?
我要创建一个应用程序。字段(电子邮件)可能/可能不会显示在第 2 步,这取决于第 1 步选择的选项。问题是我不能输入email: Yup.string().Required(),这会导致验证一直运行,即使字段不显示。
【问题讨论】:
标签: reactjs yup react-hook-form
我通过转换即时修改架构
const updateUserValidator = yup.object().shape({
email: yup.string(),
updateBy: yup.string()
}).transform(function (current, original) {
this.fields.email = original?.email?.length === undefined ? yup().string().email() : yup().string().email().required()
return current;
})
【讨论】:
您可以设置一个额外的布尔键,其中值默认为 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'),
});
这是documentation reference 相同的。
更新:
Here 是工作代码框。我添加了带有display:none; 的复选框,并在数据上下文中添加了默认状态值。
【讨论】:
isEmail 来自第 1 步并在第 2 步中使用它。@Nik @Dharman 你对这些东西有进一步的解决方案吗?谢谢。
您需要手动处理,而不是必需的。只是你需要保持每个字段的状态。并检查它的值是否存在,然后您需要显示它。 有的这样
const [email, setEmail]= useState(null);
const onChange=(e)=>{
setEmail(e.target.value)
}
return (
<input type="text" onChange={onChnage}/>
)
然后将此电子邮件传递给您的父母,在那里您检查验证。如果 email 中有任何内容,请显示它进行其他验证。或者如果它是空的或 Null 则不要显示它。
谢谢
【讨论】: