Javascript and Form Validation


What is Form Validation?

 

Implementing Data Completeness Checking with Javascript:

 

Code Example:

A functional example of data completeness checking is available. This is the code in the example:
<html>
<head>
<title>Form Validation Example</title>
<script language="Javascript" type="text/javascript">
function checkData() {
		<!--
		// Checkboxes and Radio Buttons
		var Selected = false;
		for (i = 0; i < example.color.length; i++) {
		if (example.color[i].checked)
		Selected = true;
		}
		if (!Selected) {
		alert("Please specify your favorite color.");
		return (false);
		}

		var Selected2 = false;
		for (i = 0; i < example.classes.length; i++) {
		if (example.classes[i].checked)
		Selected2 = true;
		}
		if (!Selected2) {
		alert("Please indicate at least one class you have taken.");
		return (false);
		}

		// Select Boxes
		if (example.track.selectedIndex <= 0) {
		alert("Please specify your INP track.");
		example.track.focus();
		return (false);
		}

		// Text Input Fields and Textareas
		if (document.example.fname.value == "") {
		alert("Please enter your first name.");
		document.example.fname.focus();
		return false; }

		if (document.example.lname.value == "") {
		alert("Please enter your last name.");
		document.example.fname.focus();
		return false; }

		if (document.example.hobbies.value == "") {
		alert("Please enter at least one hobby of yours.");
		document.example.hobbies.focus();
		return false;
		}
	}
	// -->
</script>
</head>
<body>
<h1>INP Student Profile</h1>
<form method="post" action="" name="example" onsubmit="return checkData()">

First Name: <input type="text" name="fname" id="fname" size="10" maxlength="15" />

<p>Last Name: <input type="text" name="lname" id="lname" size="10" maxlength="15" /></p>

<p>Favorite Color: <input type="radio" name="color" value="blue" /> blue
<input type="radio" name="color" value="green" /> green</p>

<p>Hobbies: <textarea name="hobbies" id="hobbies" rows="3"
 cols="20" wrap="wrap"></textarea></p>

<p>INP Track: <select name="track">
<option>Please choose</option>
<option value="Design">Design</option>
<option value="Technical">Technical</option>
</select></p>

<p>Classes taken: <input type="checkbox" name="classes" value="150" /> 150
<input type="checkbox" name="classes" value="210" /> 210</p>
<p><input type="submit" value="Create My Profile" /></p>
</form>
</body>
</html>

Close Window