如何在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
相关产品推荐
相关产品推荐

