是的,验证输入依赖

时间:2021-06-24 11:12:23

标签: javascript reactjs formik yup

大家好,我有以下验证:

const questionAddValidation = Yup.object().shape({

  questions: Yup.array().of(
    Yup.object({
      question: Yup.string().required().min(100)
       
      level: Yup.string().required().when("question", {
                 is: (value) => value.length > 0,
                 then: Yup.string().required(),
              }),

      answers: Yup.array().of(
        Yup.object({
          answer: Yup.string().required().min(1).when("question", {
                 is: (value) => value && value.length > 0,
                 then: Yup.string().required(),
              }),
        })
      ),
    })
  ),

我想要做的是,如果用户将在 question 输入中为其他输入输入内容,则应该可以使用 required() 方法。

我尝试以下操作:

  is: (value) => value.length > 0

但它不起作用, Unhandled Rejection (TypeError): Cannot read property 'length' of undefined 你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您只需在 required() 之前删除 when

 level: Yup.string().when("question", {
    is: (value) => value.length > 0,
    then: Yup.string().required(),
 }),
相关问题