【问题标题】:Conditionaly required one or another field - Yup有条件地要求一个或另一个字段 - 是的
【发布时间】:2020-11-11 23:48:42
【问题描述】:

我发现这解释起来有点复杂,并且没有找到任何解决方案。

我的架构中有 3 个字段。如果 field1 为 false,则需要 field2 OR field3。我试过了,但它不起作用:

    const schema = Yup.object().shape({
          field1: Yup.boolean().required(),
          fiel2: Yup.array().when(['field1', 'field3'], {
            is: (field1, field3) => !field1 && !field3,
            then: Yup.array().required(),
            otherwise: Yup.array(),
          }),
          field3: Yup.array().when(['field1', 'fiel2'], {
            is: (field1, fiel2) => !field1 && !fiel2,
            then: Yup.array().required(),
            otherwise: Yup.array(),
          }),
        });

同样,如果 field1 为 false,则其他 2 个字段之一应该是必需的。

有什么办法吗?

【问题讨论】:

    标签: node.js backend yup


    【解决方案1】:

    当它变得更复杂时,您可以使用test

    yup.object().shape({
          field1: yup.string(),
          field2: yup.string().test({
            test: function (value) {
              const {field3, field1} = this.parent;
              if (field1 && !field3) return value != null;
              return true
            }
          }),
          field3: yup.string().test({
            test: function (value) {
              const {field1, field2} = this.parent;
              if (field1 && !field2) return value != null;
              return true
            }
          })
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-11
      • 2016-12-14
      • 2022-01-20
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      相关资源
      最近更新 更多