Example of a JavaScript enabled form.

1. Start with this form:


<STRONG>My Phonebook</STRONG>
<FORM NAME  ="phonebook" 
      METHOD="POST" 
      ACTION="http://yourHost.cs.indiana.edu:yourPort#/cgi-bin/lab7/process">
Please Enter Your: <blockquote>
Full Name:    <input type="text" name="fullname"> <br>
Phone Number: <input type="text" name="phone"> 
                   </blockquote> 
<input type="submit" value="Submit">
<input type="reset" value="Clear"> 
</FORM>


That would look like this:

My Phonebook

Please Enter Your:
Full Name:
Phone Number:


2. Write the process script.


#!/usr/bin/perl
use CGI;
$q = new CGI; 
print $q->header, 
      $q->start_html(-title=>'JavaScript Lab',
                     -bgcolor=>'white');                   
if ($q->request_method() eq 'POST') {
  print $q->dump; 
} else {
  print "Only POST is supported."; 
} 
print $q->end_html; 


3. Write a JavaScript function for Name Validation


function checkFilled(textfield) {
  if (textfield.value.length == 0) {
    alert("The field \"" + textfield.name + "\" is required.");
    textfield.focus();
    textfield.select();
    return false;
  }
  return true;
}


4. Associate the Name Validation with an Action


<input type="text" 
       name="fullname" 
       onChange="checkFilled(this)">

5. Write a JavaScript function for Phone Number Validation


// Test for phone number in proper format. This function
// is quite strict, because it's not easy to do real regular 
// expression matching in JavaScript.

function validatePhone (textfield) {
  if (textfield.value.length == 12) {
    for (var i=0; i<12; i++) {
      var theChar = textfield.value.charAt(i); 
      if (i == 3) 
        if (theChar == " ") 
          continue; 
      if (i == 7) 
        if (theChar == "-") 
          continue; 
      if (i < 3 || i > 7 || (3 < i && i < 7)) 
        if (theChar >= "0" && theChar <= "9") 
          continue; 
      alert("Please enter a phone number in the format 666 666-6666");
      textfield.focus();
      textfield.select();
      return false; 
    } return true; 
  } else {
      alert("Please enter a phone number in the format 666 666-6666");
      textfield.focus();
      textfield.select();
      return false;    
  } 
} 

6. Associate the Phone Number Validation with an Action


<input type="text" 
       name="phone" 
       onChange="validatePhone(this)">


7. Incorporate the Validation Process into the Form Submission


 
function validateForm() {
  if (!checkFilled(document.phonebook.fullname)) return false;
  if (!validatePhone(document.phonebook.phone)) return false;
  return true;
}
 
<FORM NAME="phonebook" 
      METHOD="POST" 
      ACTION="http://yourHost.cs.indiana.edu:yourPort#/cgi-bin/process"
      onSubmit="return validateForm()">

8. Now change the process script to output this HTML page (complete with the <SCRIPT> tags) when called with GET. This would complete this exercise.