是的条件验证

问题描述 投票:0回答:2

我想使用我的架构在其他字段的基础上验证一个字段。就像,如果 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'),
        }),
});
javascript reactjs typescript formik yup
2个回答
4
投票

您正在将 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
中比较它。


0
投票

我发现,对于更复杂的验证,除非你有 then 作为回调,否则你会遇到错误。

eventEndDate: Yup.string().when('dateSelector', {
    is: 'selected',
    then: () =>
      Yup.string()
        .matches(
          /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/\d{2}$/,
          "You're date needs to be in the following format: dd/mm/yy. Eg: 24/12/23",
          { excludeEmptyString: true }
        )
        .required('End date is a required field.'),
  }),
© www.soinside.com 2019 - 2024. All rights reserved.