JavaScript密码匹配验证失效:合规密码仍提示不匹配
Hey there! Let's figure out why your password validation keeps throwing that "Password doesn't match!" alert even when you input a password with letters, numbers, and uppercase characters.
核心问题:正则表达式的语法错误
Take a close look at your regex definition:
var reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$"/;
See that extra double quote " stuck at the end? That's breaking the regex literal syntax entirely. JavaScript can't parse this as a valid regular expression, so every time you run pass.match(reg), it returns null—which triggers the else branch no matter how valid your password is.
修正后的完整代码
First, remove that stray double quote. We can also make the validation check cleaner by using reg.test(pass) instead of match (since we only care if the password matches, not what parts of it match):
// 修正正则表达式,移除多余的双引号 var reg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/; var pass = document.getElementById("password").value; if (pass === "") { alert("Enter the user password"); document.getElementById("password").focus(); return false; } if (pass.length < 8) { alert("Password too short, at least 8 characters"); document.getElementById("password").focus(); return false; } // 使用test方法更高效,直接返回布尔值判断匹配结果 if (reg.test(pass)) { alert("Password is valid"); } else { alert("Password doesn't match!"); return false; }
额外优化小建议
- Use strict equality (
===) instead of loose equality (==) to avoid unexpected type coercion issues down the line. - Your regex already blocks whitespace (via
(?!.*\s)), which is great—just confirm that's an intended rule for your password requirements. - For better security, consider adding a maximum length check (e.g.,
if (pass.length > 20)) to prevent overly long passwords.
内容的提问来源于stack exchange,提问作者Gresa

