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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:20:26