Form Validation is a checking process that occurs after the user clicks the submit button but before the actual form submission. The technique shown here intercepts the submission event and passes the form data through a validation function. If the data passes the tests, the validation function returns true, which allows the form to submit; otherwise it prompts the user to complete the form properly, and the validation routine returns false, which prevents the form from completing the submission.
The following example checks that the user has entered a value in both fields of a simple logon form. In this example, validation succeeds if the user enters any value in both fields. If the user leaves either field blank, the validation function fires an alert box, prompting the user to enter some information in the appropriate box and then returns false, halting the submission process:
<html>
<head>
<title>Validation Example</title>
<script language = "JavaScript">
function filled(field) {
if (field.value == "" ||
field.value == null) 
return false;
else {
return true;
}
}
function canSubmit(form) {
// is name element filled?
if (!filled(form.name) ) {
alert("Please enter your name.");
form.name.focus();
return false;
}
// is password element filled?
if (!filled(form.password) ) {
alert("Please enter your password.");
form.password.focus();
return false;
}
//Passed the tests!
return true;
}
</script>
</head>
<body>
<form method="post" action="someActionScript"
enctype="text/plain" onSubmit = "return
canSubmit(this)">
<p>Contact Us</p>
<table border="0" cellpadding="4"
cellspacing="0">
<tr>
<td>User Name</td>
<td>
<input type="text" name="name" size="56"
tabindex="1">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="password"
size="56" tabindex="2">
</td>
</tr>
<td>
<input type="submit" value="Log In"
name="send" tabindex="3">
</td>
</tr>
</table>
</form>
</body>
</html>
You use the form's onSubmit attribute to intercept form submission. The example calls the canSubmit function and passes the form itself to the function. If the canSubmit function returns true, the form is submitted. If it returns false, the submission is interrupted and the user is prompted to enter something in the appropriate field. Admittedly, you'll want a better mechanism for logging in to sensitive areas but you get the idea.
These scripts are among those most requested by students in my classes. In the form I've presented them here (aside from the form validation), the scripts are components from which you can build web applications that are compatible with all three major browsers. Next month, I'll discuss form validation with the depth it deserves.