为什么Javascript无法验证我的html代码?

时间:2019-09-23 02:07:12

标签: javascript html forms

这是我第一次尝试使用javascript和表格;由于某种原因,我的html网站元素未得到验证,我不确定为什么。我使用此表单的目的是尝试验证旁边带有“ *”的元素。由于某些原因,唯一要验证的元素是电子邮件,而没有别的。名称,日期,复选框都没有。我一直在寻找解决方法,但似乎没有任何效果。

<!doctype html>
<html>
<head>
    <link href="styles.css" rel="stylesheet">
    <script src="script.js"></script>
    <meta charset="utf-8">
    <title>Form</title>
</head>

<body>
<div class="container">

    <h1>Travel Reservation Form</h1>
    <h4>* denotes mandotory field</h4>
    <form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">


        <fieldset>
            <legend>Personal Details</legend>
            <label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
            <br><br>

            <label class="align">Email<span>*</span></label>
            <input type="email" name="mail" placeholder="james@gmail.com">
            <br><br>

            <label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">

        </fieldset>
        <br>

        <label>Select Tour Package<span>*</span>:</label>
        <select name="package">
            <option value="1">Tokyo</option>
            <option value="2">Shanghai</option>
            <option value="3">Bangkok</option>
            <option value="4">Jakarta</option>
            <option value="5">Mumbai</option>
        </select>




        <label>Number of persons<span>*</span>:</label>
        <select name="party">
            <option value="1">One Adult</option>
            <option value="2">Two Adults</option>
            <option value="3">Three Adults</option>
            <option value="4">Four Adults</option>
            <option value="5">Five Adults</option>
        </select>

        <br><br>



        <label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
        <br><br>


        <p>What Intrests you the most?<span>*</span>:</p>

        <input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>

        <input class="alignp"  type="checkbox" name="interest" value="dining"> Dining <br><br>

        <input class="alignp"  type="checkbox" name="interest" value="dancing"> Dancing <br><br>

        <input class="alignp"  type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>



        <label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>



        <label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
        <input type="radio" name="tos" value="yes">I disagree





        <p>Please provide any additional information below:- </p>
        <textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>



        <button class="btn-submit" type="submit" value="Submit">Submit</button>
        <button class="btn-reset" type="reset" value="Reset">Reset</button>

    </form>
</div>
</body>
</html>

这是在html中链接的javascript。我不确定问题出在我的html代码还是我的javascript。

// JavaScript Document
function validateForm()
{
    var name = document.forms["myForm"]["name"].value;
    var email = document.forms["myForm"]["email"].value;
    var dob = document.forms["myForm"]["DOB"].value;
    var packages = document.forms["myForm"]["package"].value;
    var arrival = document.forms["myForm"]["arrival"].value;
    //var interest = document.forms["form"]["interest"].value;
    var ToS = document.forms["myForm"]["tos"].value;
    var checkbox = document.querySelector('input[name="interest"]:checked');
    var matches = name.match(/\d+/g);


    if (matches != null) {
        alert("Name has a number in it!");
    }

    if (name == "") {
        alert("Name must be filled out");
        return false;
    }

    if (email == "") {
        alert("Email must be filled out");
        return false;
    }

    if (dob == "") {
        alert("Date of Birth must not be empty");
        return false;
    }

    if (arrival == "") {
        alert("Arrival Date must not be empty");
        return false;
    }
    if(ToS == false) {
        alert("You must agree to the Terms of Service");
        return false;

    }

    if(validateEmail(email) == false){
        alert("Must enter a valid email");
    }


    re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

    if(dob != '' && !dob.match(re)) {
        alert("Invalid date format");
        return false;
    }

    if(arrival != '' && !arrival.match(re)) {
        alert("Invalid arrival date format") ;
        return false;
    }

    if(name.length >= 30){
        alert("Name must be less than 30 characters!");
        return false;

    }

    if(!checkbox){
        alert("Please select an interest!");
        return false;
    }

}

function validateEmail(email)
{
    return /\S+@\S+\.\S+/.test(email);
}

1 个答案:

答案 0 :(得分:0)

所以我不知道您的PHP表单做了什么,所以实际上我现在只提取了所有表单代码。有很多小问题,但有诚实的错误。示例:如果要继续验证其余字段,则不需要每次验证后都返回return语句。我将一些单独的验证合并到if / else中,因为它们是同一字段上的验证。自从转储表单代码以来,我就使用ID来简化生活。随时交换回您想要的东西。由于日期字段返回YYYY / MM / DD,因此我也更新了您的正则表达式。由于这不会在任何地方发布,因此您可以使用它一段时间,然后再重新绑定到php表单中。我还检查了30个字符,并在名称中添加了最大字段长度。您还可以设置日期字段的最小和最大日期范围,以及其他一些设置,以帮助使字段本身更加安全。也有一些库可以为您处理这类事情,您不必重新发明轮子,但是如果您只是想尝试一下它,那应该会让您入门。祝你好运

<!doctype html>
<html>

<body>
  <div class="container">

    <h1>Travel Reservation Form</h1>
    <h4>* denotes mandotory field</h4>


    <fieldset>
      <legend>Personal Details</legend>
      <label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
      <br><br>

      <label class="align">Email<span>*</span></label>
      <input id="email" type="email" name="mail" placeholder="james@gmail.com">
      <br><br>

      <label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">

    </fieldset>
    <br>

    <label>Select Tour Package<span>*</span>:</label>
    <select id='package' name="package">
      <option value="1">Tokyo</option>
      <option value="2">Shanghai</option>
      <option value="3">Bangkok</option>
      <option value="4">Jakarta</option>
      <option value="5">Mumbai</option>
    </select>




    <label>Number of persons<span>*</span>:</label>
    <select name="party">
      <option value="1">One Adult</option>
      <option value="2">Two Adults</option>
      <option value="3">Three Adults</option>
      <option value="4">Four Adults</option>
      <option value="5">Five Adults</option>
    </select>

    <br><br>



    <label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
    <br><br>


    <p>What Intrests you the most?<span>*</span>:</p>

    <input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>

    <input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>

    <input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>

    <input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>



    <label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>



    <label>Terms and Conditions<span>*</span>
      <input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
    <input type="radio" name="tos" id="unaccepted" value="disagree">I disagree





    <p>Please provide any additional information below:- </p>
    <textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>



    <button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>



  </div>

  <script>
    // JavaScript Document
    function validateForm() {
      var name = document.getElementById("name").value;
      var email = document.getElementById("email").value;
      var dob = document.getElementById("dob").value;
      //Select Box
      var e = document.getElementById("package");
      // Selected Item
      var packages = e.options[e.selectedIndex].value;
      var arrival = document.getElementById("arrival").value;
      //var interest = document.getElementById("").value;
      var tos = document.querySelector('input[name="tos"]:checked').value;
      //var checkbox = document.getElementById("").value;;
      var matches = name.match(/\d+/g);
      var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;

      if (!name) {
        alert("Name must be filled out");
      } else {
        if (matches != null) {
          alert("Name has a number in it!: " + name);
        }
      }
      if (!email) {
        alert("Email must be filled out");
      } else {
        if (validateEmail(email) == false) {
          alert("Must enter a valid email: " + email);
        }
      }
      if (!dob) {
        alert("Date of Birth must not be empty");
      } else {
        if (!dob.match(re)) {
          alert(" Dob has Invalid date format: " + dob);

        }
      }
      if (!arrival) {
        alert("Arrival Date must not be empty");
      } else {
        if (!arrival.match(re)) {
          alert(" Dob has Invalid date format: " + arrival);

        }
      }
      if (tos != "agree") {
        alert("You must agree to the Terms of Service");
      }
    }

    function validateEmail(email) {
      return /\S+@\S+\.\S+/.test(email);
    }
  </script>
</body>

</html>