2017-03-01 155 views
0

我在使用Javascript驗證表單時遇到問題。我嘗試了一堆不同的東西,但我無法讓它工作。這可能是我錯過了一些完全基本的東西,我很新。請讓我知道我可能會改變什麼。Javascript無法通過驗證

<!DOCTYPE html> 
 

 
<html lang = "en"> 
 
<head> 
 
\t <title> </title> 
 
\t <meta charset = "utf-8" /> 
 
\t 
 
</head> 
 
<body> 
 
\t <script lang = "text/javascript"> 
 
\t 
 
\t document.getElementById("myForm").onsubmit = validateForm(); 
 
\t 
 
\t function zipcheck(sZip) 
 
\t { 
 
\t \t var postalRegex = /^d{5}(-\d{4})?$/; 
 
\t \t return postalRegex.test(sZip); 
 
\t } 
 
\t function validateForm() 
 
\t { 
 
\t \t if (zipcheck(document.getElementById("zip")) 
 
\t \t \t return true; 
 
\t \t else 
 
\t \t { 
 
\t \t \t alert(document.getElementById("zip") + " is not a valid zip code"); 
 
\t \t \t return false; 
 
\t \t } 
 
\t } 
 
\t </script> 
 
\t <form id = "myForm" action = "" > 
 
\t <p> 
 
\t 
 
\t <label> Zip Code 
 
\t \t <input type = "text" id = "zip" /> 
 
\t </label> 
 
\t 
 
\t <input type = "submit" name = "submit" /> 
 
\t 
 
\t </p> 
 
\t </form> 
 
\t 
 
</body> 
 
</html>

回答

1

的問題你的是,檢查HTML元素不是值。它應該是document.getElementById("zip").value

document.getElementById("myForm").onsubmit = validateForm; 
 
\t 
 
\t function zipcheck(sZip) 
 
\t { 
 
\t \t var postalRegex = /^d{5}(-\d{4})?$/; 
 
\t \t return postalRegex.test(sZip); 
 
\t } 
 
    
 
\t function validateForm() 
 
\t { 
 
\t \t if (zipcheck(document.getElementById("zip").value)){ 
 
\t \t \t return true; 
 
\t \t }else 
 
\t \t { 
 
\t \t \t alert(document.getElementById("zip").value + " is not a valid zip code"); 
 
\t \t \t return false; 
 
\t \t } 
 
\t }
<!DOCTYPE html> 
 
<html lang = "en"> 
 
<head> 
 
\t <title> </title> 
 
\t <meta charset = "utf-8" /> 
 
</head> 
 
<body> 
 
\t <form id = "myForm" action="/test" method="get" > 
 
\t <p> 
 
\t <label> Zip Code 
 
\t \t <input type = "text" id = "zip" /> 
 
\t </label> 
 
\t <input type = "submit" name = "submit" /> 
 
\t </p> 
 
\t </form> 
 
</body> 
 
</html>

這裏是jsfiddlerhttps://jsfiddle.net/u9suy516/

可選信息工作示例:使用addEventListener時,你也必須在使用preventDefault()功能通過event參數,但不需要return陳述。

function validateForm(event) 
{ 
    if (!zipcheck(document.getElementById("zip").value)) { 
     alert(document.getElementById("zip").value + " is not a valid zip code"); 
     event.preventDefault(); 
    } 
} 
+0

感謝您的快速響應!我對代碼進行了這些更改,但仍未驗證表單。 – NerevarineKing

+0

添加I編輯的答案,其他一些地區wheren't正確 –

+0

'的document.getElementById( 「myForm的」)的onsubmit = validateForm();'應該是'的document.getElementById( 「myForm的」)的onsubmit = validateForm;'或'document.getElementById(「myForm」)。addEventListener(「submit」,validateForm)' –