需要帮助使用 JavaScript 设置最小字符数

Need help setting a minimum number of characters using JavaScript

本文关键字:字符 设置 JavaScript 帮助      更新时间:2023-09-26

我正在尝试为密码字段设置至少 5 个字符,但它不起作用。每次我输入 0 或 1 个字符时它都可以工作,但在输入 2 到 5 个字符时挑战不起作用。有人可以看看我有什么并告诉我哪里出错了?

<fieldset>
    <legend>Password</legend>
      <label>Create Password</label>
        <input type="password" name="password" id"password"><br /><br />
      <label>Confirm Password</label>
        <input type="password" name="confirmPassword" id="confirmPassword">
   </fieldset><br />  


if (document.sample.password.value <=5) {
         alert("Password must contain 5 characters.");
         document.sample.password.select();
         document.sample.password.style.backgroundColor="yellow";
         return true;    // leave now 
}

将其更改为:

    <fieldset>
    <legend>Password</legend>
      <label>Create Password</label>
        <input type="password" name="password" id="password"><br /><br />
      <label>Confirm Password</label>
        <input type="password" name="confirmPassword" id="confirmPassword">
   </fieldset><br />  


if (document.getElementById('password').length<=5) {
         alert("Password must contain 5 characters.");
         document.getElementById('password').select();
         document.getElementById('password').style.backgroundColor="yellow";
         return true;    // leave now 
}

请注意 HTML 中添加的=,以便id"password"