Vue3+Yup实现按成员类型的条件表单验证需求求助
Vue3 + Yup 实现成员类型的条件表单验证方案
需求回顾
- 成员类型为企业(值为
true):税号tax必填,手机号phone非必填 - 成员类型为个人(值为
false):手机号phone必填,税号tax非必填
实现方案
Yup提供了when方法用于实现条件验证,以下两种方式都能满足需求:
方式1:将成员类型作为外部上下文变量
适合成员类型是表单外独立控制的场景(比如单独的开关组件):
setup() { const memberType = ref(false); // false=个人,true=企业 const validationSchema = Yup.object().shape({ phone: Yup.string().trim().when('$memberType', { is: false, // 个人类型触发 then: schema => schema.required().label("手机号"), otherwise: schema => schema.notRequired() }), tax: Yup.string().trim().when('$memberType', { is: true, // 企业类型触发 then: schema => schema.required().label("税号"), otherwise: schema => schema.notRequired() }) }); const { handleSubmit } = useForm({ validationSchema, context: { memberType } // 传入上下文供Yup访问 }); const submit = handleSubmit(async values => { console.log("提交数据:", values); }); return { memberType, submit }; }
方式2:将成员类型作为表单字段
更贴合常规表单设计,把成员类型纳入表单字段体系:
setup() { const validationSchema = Yup.object().shape({ memberType: Yup.boolean().required().label("成员类型"), phone: Yup.string().trim().when('memberType', { is: false, then: schema => schema.required().label("手机号"), otherwise: schema => schema.notRequired() }), tax: Yup.string().trim().when('memberType', { is: true, then: schema => schema.required().label("税号"), otherwise: schema => schema.notRequired() }) }); const { handleSubmit, register } = useForm({ validationSchema }); const submit = handleSubmit(async values => { console.log("提交数据:", values); }); return { register, submit }; }
关键说明
when方法的第一个参数:如果是上下文变量需加前缀$,如果是表单字段直接写字段名is指定触发条件,then/otherwise分别定义对应场景的验证规则- 移除固定的
required(),改为根据成员类型动态切换必填状态
内容的提问来源于stack exchange,提问作者kadirklc
相关产品推荐
相关产品推荐

