两种情况在什么时候在YUP中反应

人气:305 发布:2023-01-03 标签: reactjs formik yup

问题描述

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

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

推荐答案

当前,您正在检查两个字段是否都为真,若要检查其中一个字段为真,您需要重写IS属性以函数返回布尔值:

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

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

24