繁体   English   中英

密码验证在登录表单中不起作用

[英]Password validation is not working in the login form

密码验证在登录表单中不起作用。 这是我的代码:

function verifyPassword() {
  var str = document.getElementById("t1").value;
  if (str.match(/[a-z]/g) &&
    str.match(/[A-Z]/g) &&
    str.match(/[0-9]/g) &&
    str.match(/[^a-zA-Z\d]/g) &&
    str.length >= 8)
    return true;
  else
    return false;
}

您应该在密码字段的change事件和/或表单的提交事件中调用 function,而不是表单的click事件。 你需要测试返回值并做一些事情。

document.getElementById('t1').addEventListener('change', function() {
    if (!verifyPassword()) {
        alert("Invalid password");
    }
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
    if (!verifyPassword()) {
        event.preventDefault();
        alert("Invalid password");
    }
}

下面你有一个更清晰的代码并且正在检查你的密码,你必须有:小写字母、大写字母和一个数字。 ^符号表示密码必须按以下顺序排列:小写、大写、数字,并且必须超过 8 个字符。

语法?=.*[x]意味着您的字符串中必须包含条件x

(lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.您的旧代码仅检查您的字符串是否包含其中任何(小写、大写字符、数字),但没有设置您必须拥有所有这些的条件,并且对于您的密码系统来说,这是无用的。

 function verifyPassword() { var str = document.getElementById("t1").value; var regEx = new RegExp("^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.{8,})"); if (regEx.test(str) && str.length >= 8) console.log("good") else console.log("bad") }
 <div class="txt_field"> <input type="password" id="t1" value="" required> <label>Password</label> <button onclick="verifyPassword()">Verify</button> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM