是的:如何仅在字段存在时验证字段?

问题描述

是否可以仅在字段存在时对其进行验证?

我要创建一个应用程序。字段(电子邮件)可能会/可能不会在步骤 2 中显示,这取决于步骤 1 的所选选项。问题是我不能放email: Yup.string().required(),它导致验证一直运行,即使字段没有显示

解决方法

可以设置一个附加的布尔键,其中值是默认假。它更改为true,当你修改这个值在步骤1然后,如果值为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是工作codesandbox。我已经添加复选框与display:none;,并添加在数据上下文的默认状态值。

,

您需要手动处理,而不是必需的。只是你需要保持每个字段的状态。并检查它是否存在其值,然后您需要显示它。 有些像这样

const [email,setEmail]= useState(null);

const onChange=(e)=>{
setEmail(e.target.value)
}

return (


<input type="text" onChange={onChnage}/>
)

并将这封电子邮件传递给您的父母,您在那里检查验证。如果电子邮件 中有任何内容,则显示它进行其他验证。或者如果它为空或 Null 则不显示它。

谢谢

,

我通过转换即时修改架构

  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;
        })

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...