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

React中使用Yup条件验证遇‘expected 1 argument’错误的解决办法

解决Yup when条件验证的"expected 1 argument"错误

你的问题出在.when()配置中then和otherwise的写法不符合Yup的API规范,同时可以优化部分逻辑:

错误原因

Yup的.when()方法中,then和otherwise字段应该接收当前schema作为参数的函数,或者直接是一个schema实例,但你直接重新创建了Yup.string(),导致语法不匹配,触发"expected 1 argument"错误。

修正后的代码

email: Yup.string()
  .label('Email professionnel')
  .when('validateEmailExist', { // 单个依赖项可直接写字段名,无需数组
    is: true,
    then: (schema) => schema.test(
      'emailexists',
      'Email déjà utilisé !',
      async (value) => {
        if (!value) return true; // 空值直接通过,后续可由required验证
        try {
          const response = await axios.get<boolean>(`/api/resources/existEmail/${companyId}/${value}`);
          return !response.data; // 接口返回true表示已存在,验证不通过,返回false
        } catch (error) {
          return false; // 接口报错时默认验证不通过
        }
      }
    ),
    otherwise: (schema) => schema
      .matches(/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/, 'Le champ "Email professionnel" doit être un email valide.')
      .required(),
  }),

关键修改点

  • 将then和otherwise改为接收当前schema的函数,复用已有的string()schema(包含之前的label配置),符合Yup的API要求。
  • 简化了test函数的逻辑,直接返回!response.data,避免冗余的if判断。
  • 单个依赖项时,.when()的第一个参数可以直接写字段名'validateEmailExist',无需用数组包裹(数组写法也支持,但单个字段更简洁)。
  • 增加了空值的处理:当value为空时直接返回true,因为otherwise分支已经包含required()验证,空值会在该分支被拦截。

内容的提问来源于stack exchange,提问作者salim khamadj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:32:35