如何在 javascript 中验证密码

How to validate a password in javascript

这是我写的代码,即使密码在范围(4-12)内,它也会returns每次提示。

function PasswordCheck() {
  var str = document.getElementById("Password");
  if (str > 4 && str < 12) {
    return true;
  } else {
    alert("invalid password, your password needs to have 4-12 letters");
    return false;
  }
}

您需要使用 value 检索元素中的文本。

然后您想使用 str 字符串的 length 属性 检查字符串的长度。

function PasswordCheck() {
  var str = document.getElementById("Password").value;
  if (str.length > 4 && str.length < 12) {
    return true;
  } else {
    alert("invalid password, your password needs to have 4-12 letters");
    return false;
  }
}

这是因为 getElementById returns an Element 对象而不是直接的值。