Search code examples
javascriptreactjsyup

Problems in conditional validation with Yup


In two fields with validation, one of them, needs to be requested if the other has not filled in and vice versa Doing it that way

       email: yup.string().email().when('phone', {
        is: (phone) => !phone || phone.length === 0,
        then: yup.string().email().required(),
        otherwise: yup.string()
    }),
    phone: yup.string().when('email', {
        is: (email) => !email || email.length === 0,
        then: yup.string().required(),
        otherwise: yup.string()
    })
});

In my way I have the following error: "Error: Cyclic dependency, node was: value"


Solution

  • What you can do is to create a Shape

    const obj = yup.object().shape({
      email: yup.string().email()
        .when('phone', {
          is: (phone) => !phone || phone.length === 0,
          then: yup.string().email().required(),
          otherwise: yup.string()
        })
      phone: yup.string()
        .when('email', {
          is: (email) => !email || email.length === 0,
          then: yup.string().required(),
          otherwise: yup.string()
        })
    }, ['email', 'phone'])