【问题标题】:Yup: How to validate field only when it exists?是的:如何仅在字段存在时验证字段?
【发布时间】:2021-04-13 06:00:30
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs yup react-hook-form


    【解决方案1】:

    我通过转换即时修改架构

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

    【讨论】:

      【解决方案2】:

      您可以设置一个额外的布尔键,其中值默认为 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 你对这些东西有进一步的解决方案吗?谢谢。
      • 这两个步骤的表格是否不同?还是只是一个单一的形式分步?
      • 两个步骤的表格不同
      • 哦,好的。您可以根据第 1 步的表单值设置 initialSchema。由于您知道是否显示电子邮件字段,因此您可以修改第二步表单的 initialSchema 并根据相同的值重新初始化表单。你能提供你的代码的sn-p代码吗?
      • 请查看code snippet。我不知道如何根据步骤 1 设置初始模式并使用它。你有什么例子吗?
      【解决方案3】:

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

      const [email, setEmail]= useState(null);
      
      const onChange=(e)=>{
      setEmail(e.target.value)
      }
      
      return (
      
      
      <input type="text" onChange={onChnage}/>
      )

      然后将此电子邮件传递给您的父母,在那里您检查验证。如果 email 中有任何内容,请显示它进行其他验证。或者如果它是空的或 Null 则不要显示它。

      谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 2011-01-06
        • 2013-10-16
        • 1970-01-01
        相关资源
        最近更新 更多