简单验证器不起作用,是自定义验证器的新用户

时间:2016-10-10 15:06:03

标签: javascript html css validation

嘿伙计们这里的基本问题我遇到了麻烦。这是我第一次从头开始编码验证,无法弄清楚它们为什么不起作用。当我单击我的提交按钮时,它会转到“找不到您的文件”页面。它根本不承认我的验证器。一般来说,验证器的输入,以及如何改进或修复它将非常感激。

<DOCTYPE!>
<html>
  <head>
      <script src="gen_validatorv4.js" type="text/javascript"></script>

      <link rel="stylesheet" type="text/css" href="style.css">

      <body>
        <div id= "videoGameCircuit">
          <img src="Images/vg.jpg" width="900" height="400" alt="video game circuit" />
        </div>
        <div>
            <form action="myForm" onsubmit="return validateForm()" method="post">
            Name: <input type="text" name="name" value="" size="25" maxlength="50" /><br>
            Email: <input type="text" name="email" value="" size="25" maxlength="50" /><br>
            <input type="submit" name="submit" value="sign me up!" />
          </form>
          <script type="text/javascript">
          var frmvalidator  = new Validator("myForm");
          //where myform is the name/id of your form

          var ele = myForm; ele.addEventListener("submit", function(e){e.preventDefault();
      

          frmvalidator.EnableOnPageErrorDisplaySingleBox();
          frmvalidator.EnableMsgsTogether();


           frmvalidator.addValidation("name","req","Please enter your name");
           frmvalidator.addValidation("name","maxlen=20",	"Max length for name is 20");
           frmvalidator.addValidation("name","alpha_s","Name can contain alphabetic chars only");
          </script>
        </div>
      </body>
  </head>
</html>

1 个答案:

答案 0 :(得分:0)

在您的情况下,您需要在进行验证之前停止默认提交表单。

所以在你的情况下是这样的。

var frmvalidator  = new Validator("myForm");
      //where myform is the name/id of your form
      frmvalidator.EnableOnPageErrorDisplaySingleBox();
      frmvalidator.EnableMsgsTogether();
      frmvalidator.addValidation("name","req","Please enter your name");
      frmvalidator.addValidation("name","maxlen=20",    "Max length for name is 20");
      frmvalidator.addValidation("name","alpha_s","Name can contain alphabetic chars only");
//add id to form like id="myForm"
document.querySelector("#myForm").addEventListener("submit", function(e){
    e.preventDefault();    //stop form from submitting
    //run your validation code
    var valid = frmvalidator.valid();//your custom validation method
    if(!valid){
       //alert to user
    }
    else {
      //submit form
      e.submit();
    }
});

希望这有帮助。