Javascript表单验证不检查给定变量

时间:2013-02-18 01:32:38

标签: javascript validation

我正在尝试使用Javascript验证表单,但密码长度检查不起作用,但代码中没有明显的错误,我可以看到。

形式:

<form id="reg_form" onsubmit="return false;">
        <input type="text" maxlength="255" placeholder="Email..." name="email" /><br />
        <input type="password" placeholder="Password..." name="password" /><br />
        <input type="text" maxlength="30" placeholder="Username..." name="username" /><br />
        <input type="text" maxlength="255" placeholder="First Name..." name="fname" /><br />
        <input type="text" maxlength="255" placeholder="Last Name..." name="lname" /><br />

        <!-- Start Div With reCaptcha In -->

        <!-- End Div With reCaptcha In -->

        <input type="submit" value="Sign-up" onclick="register(this.form, this.form.email, this.form.password, this.form.username, this.form.fname, this.form.lname);" />
    </form>

Javascript功能:

<script>
  function register(form, email, password, username, fname, lname) {
    document.getElementById("reg_error").style.display = "block";
    if (email.value.length < 1) {
      document.getElementById("reg_error").innerHTML = "Please Enter An Email Address!";
      return;
    }
    if (password.value.length < 6) {
      document.getElementById("reg_error").innerHtml = "Passwords Must Be Longer Than 6 Characters!";
      return;
    }
    if (username.value.length < 5 || username.value.length > 30) {
      document.getElementById("reg_error").innerHTML = "Username Must Be Between 5 And 30 Characters Long!";
      return;
    }
    if (fname.value.length < 1) {
      document.getElementById("reg_error").innerHTML = "Please enter a first name!";
      return;
    }
    if (lname.value.length < 1) {
      document.getElementById("reg_error").innerHTML = "Please enter a last name!";
      return;
    }
    var info = new FormData();
    info.append("email", email.value);
    info.append("p", hex_sha512(password.value));
    password.value = "";
    info.append("username", username.value);
    info.append("fname", fname.value);
    info.append("lname", lname.value);
    if (window.XMLHttpRequest) {
      register_ = new XMLHttpRequest();
    } else {
      register_ = new ActiveXObject("Microsoft.XMLHTTP");
    }
    register_.onreadystatechange = function () {
      if (register_.readyState == 4 && register_.status == 200) {
        document.getElementById("reg_error").innerHTML = register_.responseText;
      }
    }
    register_.open("POST", "scripts/signup.php", true);
    register_.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    register_.send(info);
  }
</script>

除了查询密码值长度的if语句之外,所有if语句都能正常工作。任何帮助,将不胜感激。正如我通过console.log();

测试的那样,这些值正确传递

我正在使用HTML5 Boilerplate。我不想使用jQuery来做这件事。

1 个答案:

答案 0 :(得分:0)

你在这部分拼错了innerHTML

if (password.value.length < 1) {
    document.getElementById("reg_error").innerHtml = ...

将其更改为:

document.getElementById("reg_error").innerHTML = ...