我在使用 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/