Problems in conditional validation with Yup
Asked Answered
C

2

6

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"

Contour answered 29/1, 2020 at 20:41 Comment(0)
S
7

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'])
Spasm answered 29/1, 2020 at 20:45 Comment(3)
It worked for me, too, thank you! Can you please explain what the array at the end does? That was I needed to add, but I don't see what is gained by this.Chap
How we can do this in typescript ? Because when I add the array at the bottom, it will work but it still complains Type 'string' is not assignable to type '[string, string]'.ts(2322)Harv
For anyone else struggling with this in TypeScript, I found that using [['email', 'phone']] rather than ['email', 'phone'] (so wrap the values in square braces) fixed this issue. This may have been because I was dealing with Yup array thoughPickar
T
1
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'])
Tinned answered 13/3, 2023 at 6:15 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Shevat

© 2022 - 2024 — McMap. All rights reserved.