【问题标题】:Yup conditional validation是的条件验证
【发布时间】:2021-08-18 22:42:42
【问题描述】:

我想使用我的架构在其他字段的基础上验证一个字段。比如,如果 carType 是“SUV”,则最大“noOfPassengers”应该是 6,否则是 4。但是,它没有验证这种情况,我既不能调试它,也不能在控制台中得到任何错误。

const validationSchema = yup.object().shape({
    location: yup
        .string()
        .required('location is required'),
    destination: yup
        .string()
        .required('Destination is required'),
    carType: yup
        .string(),
    noOfPassengers: yup
        .string()
        .when('carType', {
            is: value => value && value === "SUV",
            then: yup
                .string()
                .max(6, 'Max 6 passengers are required'),
            otherwise: yup
                .string()
                .max(4, 'Max 4 passengers are required'),
        }),
});

【问题讨论】:

  • 你能分享你的表单代码吗?
  • 你试过简单的is: 'SUV'吗?

标签: javascript reactjs typescript formik yup


【解决方案1】:

您正在将 noOfPassengers 的值作为字符串进行比较,而它应该是这样的数字:

Yup.object().shape({
  location: Yup
      .string()
      .required('location is required'),
  destination: Yup
      .string()
      .required('Destination is required'),
  carType: Yup
      .string(),
  noOfPassengers: Yup
      .number()
      .when('carType', {
          is: value => value && value === "SUV",
          then: Yup
              .number()
              .max(6, 'Max 6 passengers are required'),
          otherwise: Yup
              .number()
              .max(4, 'Max 4 passengers are required'),
      }),
});

如果你运行这个,你应该得到验证错误。你的逻辑条件也有缺陷。你也应该解决这个问题,但这不是这个答案的范围。

问题是

Yup.string() 应该是 Yup.number(),因为您在 max 中比较它。

【讨论】:

  • 搞错了,它对我有用。谢谢!
  • 酷。如果有效,您可以接受答案。
猜你喜欢
  • 2018-12-31
  • 1970-01-01
  • 2021-06-24
  • 2021-08-24
  • 2011-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多