简体   繁体   中英

prevent form from submitting not working, JavaScript

Hello and thank you for your time.

I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.

    // form validation, makes sure that the user inputs the correct data types.         

    function validateinput(event){

    var email = document.getElementById('email').value;
    var firstname = document.getElementById('firstname').value;
    var lastname = document.getElementById('lastname').value;
    var message = document.getElementById('message').value;

    var emailFilter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    var firstnameFilter = /^([" "a-zA-Z.-])+$/;
    var lastnameFilter = /^([" "a-zA-Z.-])+$/;
    var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;



    if (!emailFilter.test(email)) {
    alert('!Enter a email. Or enter a valid email address.');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    }

    if (!firstnameFilter.test(firstname)) {
    alert('!Enter a first name. Or enter a valid name.');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    }

    if (!lastnameFilter.test(lastname)) {
    alert('!Enter a last name. Or enter a name., only letters');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    } 

    if (!messageFilter.test(message)) {
    alert('!Enter a message.');
    document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
    return false;
    } 

    alert ('Your order was submited')

    }

    document.getElementById('payment').addEventListener("submit", validateinput)

have also tried other methods thought they do not seem too work on this page but works on others ?

Like changing the var names and id,s in this one i am using on my contact page

    function validateinput(event){
      var address1 = document.getElementById('address1').value;
    var postcode = document.getElementById('postcode').value;


    var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
    var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;

    var formValid = true;

    if (!address1Filter.test(address1)) {
    alert('!Enter an address. Or enter a valid address., only letters and   numbers');
    formValid = false;
    event.preventDefault();
    return false;
    }

    if (!postcodeFilter.test(postcode)) {
    alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
    formValid = false;
    event.preventDefault();
    return false;
    } 


    alert ('Your order was submited')

    }

    document.getElementById('payment').addEventListener("submit", validateinput)

So what am I doing wrong ?

the html

    <!doctype html>

    <!-- name: Edwin martin -date: 30/11/2015 -task:  a form  with split up inputs using the
    <fieldset> & <legend> tags -->

    <html lang="en">


      <head>
        <title>contact</title>
        <script type="text/javascript" src="scripts/contact2.js"> </script> 
            <!-- ensures the document is using the correct char set --> 
              <meta charset="utf-8">
              <meta name="description" content="contact page">  

              <link rel="icon" href="images/fav.png" type="image/png"/>

            <!-- 
                   The below section looks like a comment, but it's a conditional include statement.
                   It's ignored by all browsers except IE9.  html5shiv is a library that fixes some HTML5 
                   IE bugs. 
            -->

              <!--[if lt IE 9]>
              <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
              <![endif]-->


                  <!-- pulls in the styles sheet -->
              <link rel="stylesheet" href="styles/indexstyles.css">


      </head>


            <body onload="main()">


             <!-- start of the form, id form sets the position, size, border style and color -->
             <div id="form2">

                       <!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
                        <div id="head">
                            <header id="headcolor">
                                <div id="toplinks">
                                     <ul>
                                        <li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
                                        <li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
                                    </ul>
                                </div> <br>
                                       <br>
                            </header> 
                            <h1 id="title"> Contact </h1>
                            <p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
                        </div>

                        <div id="map"> </div>


                    <!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
                    <form id="payment">
                        <!-- Contact Information section --> 
                            <fieldset>  
                                <legend> Personal Information </legend> 
                                <p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname"  placeholder="enter a first name" class="add1"></p>
                                <p> <label> Last Name(*):   </label> <input type="text" name="last_name" id="lastname"  placeholder="enter a last name" class="add1"></p>
                                <p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
                                <p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
                                <p> <label> message(*):   </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
                            </fieldset>


                        <!-- Submit button --> 

                                <input type="submit" class="submit_button"> 
                                <input type="reset" class="reset_button"> 


                    </form>

            </div>
                <script type="text/javascript" src="scripts/contact.js"> </script> 

                 <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
        </body>
    </html>

i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input

 //onload callback function
 function main() {

 console.log("in main function");
  var myForm  = document.getElementById("payment");
  myForm.addEventListener("submit",validateForm);
}

 //validate callback function 
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment"); 

if (myForm.first_name.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("firstname").className += " formInvalid"; //add  the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 

if (myForm.last_name.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 

if (myForm.email.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 

if (myForm.message.value == "") {
    formValid = false;
    //display error message 
    document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
    //stop form from submitting
    event.preventDefault();
} 
}

document.getElementById('payment').addEventListener("submit", validateinput) , the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.

document.getElementById('payment').addEventListener("submit", function(event) {
    validateinput(event);
});

I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.

<input type="submit" onclick="return validateinput();" class="submit_button">

You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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