Javascript无法获取表单进行验证

时间:2017-03-01 18:24:25

标签: javascript html

我在使用Javascript验证表单时遇到问题。我尝试了很多不同的东西,但我无法让它发挥作用。我可能错过了一些完全基本的东西,我对此很陌生。请让我知道我可能会改变什么。

<!DOCTYPE html>

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

1 个答案:

答案 0 :(得分:1)

问题是你,检查HTML元素而不是值。它应该是document.getElementById("zip").value

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

这是jsfiddler的工作示例 https://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();
    }
 }