React 中 When 中 Yup 中的两个条件

Jos*_*eph 8 reactjs yup formik

我想提出两个条件,如果它isProductisBox为真,则product_id应该是必需的。我在下面执行了这段代码,但它不起作用

 product_id: yup.string().when(['isProduct', 'isBox'], {
    is: true,
    then: yup.string().required('Select product'),
  }),
Run Code Online (Sandbox Code Playgroud)

Dip*_*hah 14

目前,您正在检查两个字段是否为 true,为了检查其中一个字段是否为 true,您需要重写 is 属性以返回布尔值的函数:

product_id: yup.string().when(['isProduct', 'isBox'], {
  is: (isProduct, isBox) => isProduct || isBox,
  then: yup.string().required('Select product'),
}),
Run Code Online (Sandbox Code Playgroud)

参考: https: //github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema