javascript 条件验证

6ju8rftf  于 2024-01-05  发布在  Java
关注(0)|答案(2)|浏览(112)

我想验证一个字段的基础上,其他使用我的模式.像,如果carType是“SUV”最大“noofPassengers”应该是6 else 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'),
        }),
});

字符串

wsewodh2

wsewodh21#

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

wi3ka0sx

wi3ka0sx2#

我发现,对于更复杂的验证,除非将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.'),
  }),

字符串

相关问题