Validation of a form

Validations are performed to ensure that the user doesn’t leave any box blank.

<body>

<form method="post" action="form.php" onsubmit="return checkIt();">	<label for="yourname">Name:</label>
			<input type="text" name="yourname" id="yourname" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>

<script>
function checkIt() {
	var theName = document.getElementById("yourname").value;
	if (theName.length < 1) {
		window.alert("Name field can NOT be blank!");
		return false;
		}
	else {
		return true;
		}	
}
</script>

</body>

The function uses an if statement to check whether the text field contains any character. If the length is less than 1, it means that the text field is left blank and the function shows an alert on the screen.

Leave a Reply