【问题标题】:Yup validation, if a field is true, check the value of another field with switch statements是的验证,如果一个字段为真,则使用 switch 语句检查另一个字段的值
【发布时间】:2022-01-17 11:00:57
【问题描述】:

假设我有 3 个字段:showDiscountdiscountTypediscountValue

showDiscount 设置为true 且discountType 为“PERCENTAGE”时,discountValue 应为必填项且应为1 到100。如果discountType 为“FIXED_AMOUNT”,discountValue 应至少为0.01.

我尝试寻找解决方案,这是我能找到的最接近的解决方案:Two Condition in When in Yup in React

应用更改后,这里是一个示例 sn-p:

const schema = yup.object().shape({
    showDiscount: yup.boolean().required(''),
    discountType: yup.string().when('showDiscount', {
      is: true,
      then: yup.string().required(),
    }),
    discountValue: yup.number().when('showDiscount', {
      is: (showDiscount) => showDiscount,
      then: yup
        .number()
        .when('discountType', (discountType, discountValueSchema) => {
          switch (discountType) {
            case 'PERCENTAGE':
              return discountValueSchema
                .typeError('Enter a number')
                .min(1, 'Enter a discount percentage of at least 1%')
                .max(100, 'Enter a discount percentage of at most 100%')
            case 'FIXED_AMOUNT':
              return discountValueSchema
                .typeError('Enter a number')
                .min(0.01, 'Enter a discount amount of at least 0.01')
            default:
              return discountValueSchema
          }
        }),
      })
    ),
})

当我尝试提交表单时,无论showDiscountdiscountType 的值如何,我都会收到以下错误:

discountValue 必须是 number 类型,但最终值为:NaN(从值 "" 转换)。

【问题讨论】:

    标签: reactjs validation yup


    【解决方案1】:

    when 可以接受多个字段,所以你应该可以这样做

    ...
    .when(['showDiscount', 'discountType'], (showDiscount, discountType, discountValueSchema) => {
    ...
    

    虽然此示例未在文档中明确显示,但您可以在此处看到提示 https://www.npmjs.com/package/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 2020-02-17
      • 2017-06-07
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2011-09-20
      相关资源
      最近更新 更多