首页 > 解决方案 > 有条件地需要一个或另一个字段 - 是的

问题描述

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

我的架构中有 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.jsbackendyup

解决方案


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

推荐阅读