You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Yup的when验证中实现类似switch的多分支金额校验

Yup实现多分支条件校验(类似switch逻辑)

你原来的写法会因为对象键重复(多个is和then)被覆盖,无法生效。下面提供两种可行的实现方式:

方式一:数组形式的多分支配置

把每个条件分支封装成单独的对象,放进数组传给when,Yup会依次匹配并应用对应规则:

const initialValues = {
  type: "",
  amount: "",
}

const validationSchema = Yup.object().shape({
  type: Yup.string(),
  amount: Yup.number()
    .when('type', [
      {
        is: 'quick',
        then: Yup.number().max(200, '快速类型金额不能超过200')
      },
      {
        is: 'long-term',
        then: Yup.number().max(400, '长期类型金额不能超过400')
      },
      {
        is: 'short-term',
        then: Yup.number().max(300, '短期类型金额不能超过300')
      }
    ])
    .required('金额不能为空')
})

方式二:函数式switch逻辑

如果逻辑更复杂,直接用函数配合原生switch语句,逻辑更直观:

const initialValues = {
  type: "",
  amount: "",
}

const validationSchema = Yup.object().shape({
  type: Yup.string(),
  amount: Yup.number()
    .when('type', (currentType, schema) => {
      switch(currentType) {
        case 'quick':
          return schema.max(200, '快速类型金额不能超过200');
        case 'long-term':
          return schema.max(400, '长期类型金额不能超过400');
        case 'short-term':
          return schema.max(300, '短期类型金额不能超过300');
        default:
          // 默认情况不添加额外限制,直接返回原schema
          return schema;
      }
    })
    .required('金额不能为空')
})

注意事项

  • 基础校验规则(比如Yup.number())写在when外面,保证所有分支都继承基础规则;
  • 可以给校验方法(比如max)添加自定义错误提示,让用户更清楚问题所在;
  • 如果需要确保type必须选择,记得给type字段添加必填校验:type: Yup.string().required('请选择类型'),避免type为空时分支规则不生效。

内容的提问来源于stack exchange,提问作者Awesome Bassey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:01:22