2016-02-27 107 views
0

我正在使用以下函數來覆蓋窗體的onsubmit行爲。但是,它仍然提交表單。javascript form submit prevent

function validate() { 

    var mainForm = document.getElementById("form"); 
    mainForm.onsubmit = function (e) { 
     e.preventDefault(); 
     alert("form submit prevented"); 
    } 

    var x = document.forms["form"]["fname"].value; 
    var y = document.forms["form"]["pname"].value; 
    var email = document.forms["form"]["email"].value; 
    var phone = document.forms["form"]["phone"].value; 
    var date = document.forms["form"]["date"].value; 
    var month = document.forms["form"]["month"].value; 
    var year = document.forms["form"]["year"].value; 


    window.load = function() { 
     var myForm = document.getElementById('form'); 
     myForm.onsubmit = function (e) { 
      return validate(); // will be false if the form is invalid 
     } 
    } 

    if(x == null || x == "" || isNaN(x) == false) { 
     alert("Check Name, It can't have numbers. You can use Roman numbers."); 
     return false; 
    } else if(y == null || y == "") { 
     alert("Picture Name must be filled out"); 
     return false; 
    } else if(email == '' || email.indexOf('@') == -1 || email.indexOf('.') == -1) { 
     //alert("Insert valid Email Address"); 
     makeRed(); 
     return false; 
    } else if(phone == '' || phone < 1000000000 || phone > 9999999999) { 

     alert("Enter valid phone number"); 
     return false; 

    } else if(date == '' || date < 01 || date > 31) { 

     alert("Enter valid Date "); 
     return false; 

    } else if(month == '' || month < 1 || month > 12) { 

     alert("Enter valid Month "); 
     return false; 

    } else if(year == '' || year < 1800 || year > 2016) { 
     alert("Enter valid Year "); 
     return false; 

    } 

    //Function used to make colors red instead of individual codelines 
    function makeRed(inputDiv) { 
     inputDiv.style.backgroundColor = "#AA0000"; 
     inputDiv.parentNode.style.backgroundColor = "#AA0000"; 
     inputDiv.parentNode.style.color = "#FFFFFF"; 
    } 

    //Function made to clean the divs when the validation is met. 
    function makeClean(inputDiv) { 
     inputDiv.style.backgroundColor = "#FFFFFF"; 
     inputDiv.parentNode.style.backgroundColor = "#FFFFFF"; 
     inputDiv.parentNode.style.color = "#000000"; 
    } 
} 
+1

將'window.load'移到'validate()'之外。 – Tushar

+0

嘗試添加e.stopPropagation();通過e.preventDefault(); –

回答

0

次要的問題,您使用:

<input type="submit"> 

相反的:

<input type="button"> 

使用後,從改變你的功能:

mainForm.onsubmit = function(e){.... 

並添加此到你的驗證功能的最後:

document.getElementById("myForm").submit(); 
+0

我正在使用input type =「submit」 – Arihant

+0

如果是我,我不會使用它,所以我沒有阻止任何事情。然後,我會使用一個按鈕,定義我的驗證功能,並使用JS提交表格,我列出。讓生活變得更容易。 – Munsterlander