最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Problems in conditional validation with Yup - Stack Overflow

programmeradmin1浏览0评论

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"

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"

Share Improve this question edited Jan 30, 2020 at 2:38 Lucas Fabre 1,9512 gold badges12 silver badges25 bronze badges asked Jan 29, 2020 at 20:41 Amado PinheiroAmado Pinheiro 631 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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'])
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'])
发布评论

评论列表(0)

  1. 暂无评论