JavaScript 无法获取表单进行验证

标签 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>

最佳答案

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

    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;
		}
	}
<!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>

这是 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();
    }
 }

关于JavaScript 无法获取表单进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539215/

相关文章:

javascript - 播放视频时停止轮播 - Bootstrap 4

html - 当其中有文本时,div 会折叠

html - CSS可以从相邻元素继承吗?

javascript - 如何更改 html 中的 javascript 数据类型值

javascript - 在 chrome 扩展中使用 fetch 发送 null origin header

javascript - 如何读取从 javascript post 调用的 python 脚本中的数据

javascript - Crypt 不是 Angular 2 中的构造函数

javascript - 制作基于 html 的计算器时如何在 javascript 中显示计算历史记录

javascript - 谷歌折线图时间显示

javascript - express - 路线分离方法