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

为何Yup密码验证仅触发min规则,不执行matches规则?

Yup密码验证matches规则不生效的问题解决

你的代码里存在一个语法错误,导致matches规则根本没有被正确执行:

在.matches(/^[a-zA-Z0-9]+$", "other message...")这一行中,正则表达式/^[a-zA-Z0-9]+$/后面多了一个多余的双引号,破坏了参数的格式,Yup无法解析这条验证规则,所以只有min规则在正常工作。

/^[a-zA-Z0-9]+$/本身是正确的——它用于限制密码只能由字母和数字组成,但因为语法错误,这条规则被完全忽略了。

修正后的代码

const validationSchema = Yup.object({
    password: Yup.string()
      .min(8, "Password must be 8 chars long")
      .matches(/^[a-zA-Z0-9]+$/, "Password must contain only letters and numbers"),
    confirmPswd: Yup.string().oneOf([Yup.ref("password"), null], "password must match"),
  });

const handleSubmit = (e) => {
    e.preventDefault();
    validationSchema
      .validate({ password, confirmPswd })
      .then(() => {
        mutate({ e, token });
      })
      .catch((error) => {
        setHelperText({ confirmPswd: error.message });
        console.error("Password is invalid", error);
      });
  };

额外提示

如果你的需求是密码必须同时包含字母和数字(而不是仅允许字母数字组合),当前正则还不够——它会允许纯数字或纯字母的密码通过。这种情况下可以改用以下正则:

.matches(/^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{8,}$/, "Password must contain at least one letter and one number")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:52:08