2016-02-27 58 views
0

調用提交的Vaidation函數。Javascript驗證不起作用(onSubmit)

HTML

<input type="submit" class="submit" value="submit"> 

JS

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

驗證()

function validate() { 

    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; 
    return false; 
    alert('wass'); 



    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"); 
     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

顯示'validate()'的定義' – hindmost

回答

0

你需要阻止默認表單提交使用:

e.preventDefault(); 

將這個上面你的驗證功能。

然後使用表單上的submit()函數實際提交表單提供您的驗證通過。

無論如何您的表單正在提交。

0

您需要通過調用e.preventDefault()來阻止表單提交的默認功能。在你的情況下:

window.load = function() { 
    document.getElementById('form').onsubmit = function (e) { 
     if (!validate()) { 
      e.preventDefault(); 
     } 
    } 
}