Validating User Input : Validation « Form Control « JavaScript DHTML

Validating User Input

<title>Form validation</title>
<script language="JavaScript">
<!-- script start
function validateComplete(formObj) {
     if (emptyField(formObj.firstName))
          alert("Please enter your first name.");
     else if (emptyField(formObj.lastName))
          alert("Please enter your last name.");
     else if (emptyField(formObj.address1)
          && emptyField(formObj.address2))
          alert("Please enter your address.");
     else if (emptyField(
          alert("Please enter your city or town.");
     else if (emptyField(formObj.state))
          alert("Please enter your state.");
     else if (emptyField(
          alert("Please enter your E-mail address.");
     else return true;
     return false;
// Check to see if field is empty
function emptyField(textObj)
     if (textObj.value.length == 0) return true;
     for (var i=0; i<textObj.value.length; ++i) {
          var ch = textObj.value.charAt(i);
          if (ch != ' ' && ch != '\t') return false;
     return true;
// script end -->

<h1>form validation</h1>
<form name="myform" action="actionURL" method="post" onSubmit="return validateComplete(document.myform)">
First Name:<input type="text" name="firstName">
Last Name: <input type="text" name="lastName">
Address:   <input type="text" name="address1">
           <input type="text" name="address2">
<input type="text" name="city" size=12>
<input type="text" name="state" size=2>
Zip Code:
<input type="text" name="zip" size=5>
Home Phone:<input type="text" name="homePhone" size=12>
Work Phone:<input type="text" name="workPhone" size=12>
FAX:       <input type="text" name="FAX" size=12>
E-mail Address: <input type="text" name="email">
Quest:          <input type="text" name="quest">
Favorite Color: <input type="text" name="favColor">
<input type="submit" name="submit" value="Submit">


Related examples in the same category

1.Form validation: Not Empty, Valid Radio, is Number, string length, EMail Address
2.Validate an input field with minimum and maximum values
3.Validate an field with a maximum number of characters
4.Phone Number Validation
5.Creating Reusable Validation Code
6.Credit Card Validation
7.Money Format
8.Validate email address
9.Validate a number
10.TextField input length validator
11.Password field validator
12.TextField validator: email, IP address and URL
13.Must be at least 3 characters and not more than 8
14.Only characters are allowed
15.Can be empty
16.Must be a valid email address
17.ComboBox(list box): Must be selected one
18.InputBox: value must be between 10 and 90
19.Not stop when the first failed validation is encountered
20.A CSS is used to highlight the fields which failed to validate
21.Need to select a file
22.A simple form with two passwords that must have the same value
23.Shows the usage of callback functions for checking a field
24.Javascript validation framework
25.Form validator library