简体   繁体   English

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

[英]Why doesn't Javascript validate my html code?

This is my first attempt at working with javascript and forms;这是我第一次尝试使用 javascript 和 forms; for some reason my html website elements aren't being validated and I am not sure why.出于某种原因,我的 html 网站元素没有得到验证,我不知道为什么。 My goal with this form is trying to validate the elements that have an '*' next to them.我使用此表单的目标是尝试验证旁边有“*”的元素。 For some reason the only element that is being validated is email and nothing else.出于某种原因,唯一正在验证的元素是 email,仅此而已。 Name, dates, the checkbox aren't.姓名,日期,复选框不是。 I have been trying to find a fix, but nothing seems to work.我一直在努力寻找解决方法,但似乎没有任何效果。

<!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>

Here is the javascript that is being linked in the html.这是 html 中链接的 javascript。 I am unsure whether the issue is with my html code or with my 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);
}

So I have no idea what your PHP form did, so I actually just pulled all the form code for now.所以我不知道你的 PHP 表格做了什么,所以我现在实际上只是提取了所有的表格代码。 There were a lot of little issues but honest mistakes.有很多小问题,但诚实的错误。 Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields.示例:如果要继续验证字段的 rest,则不需要在每次验证后返回语句。 I combined some separate validations into if/else's since they were validations on the same field.我将一些单独的验证合并到 if/else 中,因为它们是同一字段上的验证。 I used ID's to make my life easier and since I dumped the form code.我使用 ID 让我的生活更轻松,因为我丢弃了表单代码。 Feel free to swap back to what you want.随意换回你想要的。 I also updated your regex since the date field returns YYYY/MM/DD.我还更新了您的正则表达式,因为日期字段返回 YYYY/MM/DD。 Since this doesn't post anywhere you can play with it for a while, before tying back into your php form.由于这不会在任何地方发布,因此您可以暂时使用它,然后再重新输入您的 php 表格。 I also pulled the check for 30 characters and added a max field length to name.我还检查了 30 个字符并添加了一个最大字段长度来命名。 You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof.您还可以设置日期字段的最小和最大日期范围以及其他一些东西,以帮助使字段本身更加万无一失。 There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started.还有一些库可以为你处理这种事情,你不必重新发明轮子,但如果你只是想玩弄它,这应该让你开始。 Good Luck祝你好运

 <: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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM