Amado Pinheiro
Amado Pinheiro

Reputation: 63

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"

Upvotes: 6

Views: 4798

Answers (2)

Uğur Okur
Uğur Okur

Reputation: 11

const obj = yup.object().shape({
  email: yup.string().email().required()
          .when('phone', (phone, schema) => (phone[0] !== undefined ? schema.notRequired() : schema)),

  phone: yup.string().required()
    .when('phone', (email, schema) => (email[0] !== undefined ? schema.email().notRequired() : schema))
}, ['email', 'phone'])

Upvotes: 1

Lucas Fabre
Lucas Fabre

Reputation: 1951

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'])

Upvotes: 7

Related Questions