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

Yup字符串验证异常求助:混合数字字符串未被拦截

问题排查与修复

你的Yup验证失效的核心原因是语法错误导致正则测试根本没作用在city字段上:

  • 你在.required()后面多写了一个}),直接把city的链式验证提前终止了,后面的两个.test()实际上绑定到了整个表单对象上,而非city字段。这时候test函数里的val是整个表单的对象,不是用户输入的城市名,正则测试自然失效。

修复后的完整代码

const schema = yup.object({
  city: yup
    .string()
    .required("Looks like you forgot to type a city you are interested in")
    // 移除多余的}),让test方法正确挂载到city的验证链上
    .test("regex test", `Numbers can't be in a city name`, (val) => {
      const regExp = /^[a-zA-Z\s]+$/;
      return regExp.test(val as string);
    })
    .test(
      "empty string test",
      "Looks like you forgot to type a city you are interested in",
      (val) => {
        return val.trim() !== "";
      }
    )
});

额外优化建议

  • 空字符串验证可以和required合并,用.trim()配合.required()简化代码:.string().trim().required("提示语"),省去一个test方法。
  • 如果需要支持带重音符号的城市名(比如São Paulo),可以把正则调整为/^[a-zA-ZÀ-ÿ\s]+$/。

内容的提问来源于stack exchange,提问作者Seva Sleva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:52:05