NerevarineKing NerevarineKing -4 years ago 107
Javascript Question

Javascript can't get form to validate

I'm having problems getting my form to validate with Javascript. I've tried a bunch of different things, but I just can't get it to work. It's possible I'm missing something completely basic, I am pretty new at this. Please let me know what I could possibly change.



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




Answer Source

The Problem your are, checking the HTML Element not the Value. It should be

    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>

here is a working sample on jsfiddler https://jsfiddle.net/u9suy516/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download