如何更改此代码以使电子邮件表单验证正常运行?

时间:2015-04-13 21:10:42

标签: javascript

这是我的js。我正在尝试创建一个电子邮件表单验证,但它无法正常工作。每次点击提交时,它会自动将您发送到谷歌(如果输入有效,则应该将其发送给您),即使它只是空白或不正确。

var txtEmail = document.querySelector("email");
var txtFeedback = document.querySelector('#txtFeedback');
var errorDivs = document.getElementsByClassName("error");





formReference.addEventListener('submit', onFormSubmit);


function onFormSubmit(event) {


    var isValid = true;


    //clear out the feedback div
   txtFeedback.innerHTML = "";

   //clear out the error divs
   for(var i = 0; i < errorDivs.length; i++) {
    errorDivs[i].innerHTML = "";
  }


  if ( txtEmail.value == "" || !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txtEmail.value)){
isValid = false;
txtFeedback.innerHTML += "<p>Please enter a valid email address.</p>";
txtEmail.nextElementSibling.innerHTML = "Please enter a valid email    address."


  } if(!isValid) {
    event.preventDefault();
   }
}

HTML

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        #txtFeedback {
           color: #FF0000;

      }
       .error {
           display: inline;
           color: #FF0000;
      }
  </style>
</head>
<body>
<div id="txtFeedback"></div>
<form action="http://www.google.com" id="myForm">
    <div>
        <label for="email">Email:</label>
        <input id="email"/>
        <div class="error"></div>
    </div>
    <div>
        <input type="submit" value="submit" id="btnSubmit" />
    </div>
    </form>
<script src = "js/main.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的第一行选择email元素。

将其更改为选择ID为电子邮件的元素:

var txtEmail = document.querySelector("#email");

并且您未在代码中声明formReference

我宣布它是这样的,它运作得很好。

var formReference = document.getElementById('myForm');