<%response.buffer=True%> <% function rw(str) response.write str end function function html(str) response.write(server.HTMLEncode(str)) end function function url(link,str) response.write "" & str & "" end function %> [CTN162:lessons | topics]
[CTN162: Lessons & Topics]

Day 13: Form Validation

Form Validation: One of the primary jobs for which JavaScript is best suited is form validation. Since JavaScript is the one "equally" supported client side script, it is the scripting language of choice for handling a user's form. We wish to use client side script to check forms prior to server side processing, primarily to take work away from the server. It makes more sense to "validate" (check for proper data) on the client's computer prior to form submission, rather than sending the bad data back and forth to the server! Once the form is deemed acceptable by the client side JavaScript, the data is sent to the server for processing, which usually means the data is destined for automatic email generation, database submission, or both.

Apprehending Form Elements: Each form, and in turn, each form element on the page can be identified, and addressed (apprehended) using the document object model (DOM). The form itself, each element inside, and most important, the VALUE as input (or not) by the user is available:

document.formname.formelement.value

Document is a controlled word, but we substitute the name of the form, and the name of the element in the example above. To read the current value of a textbox named "FirstName" on a form named "myForm" into a variable, we could do this:

var myValue = document.myForm.FirstName.value;

From here, we can check the value to see if the user has entered correct data. The most common use of form validation is merely to determine whether a user has entered ANY data at all, and to return the user to the form element, and request that data be entered, prior to form submission.

While we can apprehend form data in the way above, we find it is difficult to do long forms in this way. Each element would need to be specifically called out by name, and dealt with accordingly. Luckily we can also look at form elements, and the data inside them, as a built-in array. We can use the for loop to access the elements in the array, and process them in turn. Here we get data from a form element via an array:

var myValue = document.forms[0].elements[0].value;

To determine what type of form element we have, we can access the "type" of the element:

var myType = document.forms[0].elements[0].type;

We can also determine what "name" has been given to the specific form element:

var myName = document.forms[0].elements[0].name;

The following example enumerates (displays) the form elements, and the current contents of the form elements (values) when you click on the links at the bottom of the Page: Form Elements

In the above example, the values change based on your input to the form. Note that the "EMPTY" is put there via the code on the page. An unfilled form value returns an empty string. Below is the function that loops through each element of the FIRST form on the page only, (document.forms[0]) and displays the name, type and value of each form element:

function formElements()
{
var myElements = "";
var thisType = "";
var thisForm = document.forms[0];

    for(x=0; x<thisForm.elements.length; x++)
   {
   myElements += "Name: " + thisForm.elements[x].name + " ";
   thisType = thisForm.elements[x].type;
   myElements += "Type: " + thisType + " ";
   if(thisType=="text"||thisType=="textarea"||thisType=="button")
       {
       if (thisForm.elements[x].value!="")
       {
       myElements += "Value: " + thisForm.elements[x].value + "\n";
       }else{
       myElements += "Value: Empty \n";
       }
   }else if(thisType=="checkbox"||thisType=="radio"){
   myElements += "Checked? " + thisForm.elements[x].checked + "\n";
   }else if(thisType=="select-one"){
   myElements += "Selected Text: " + thisForm.elements[x].options[thisForm.elements[x].selectedIndex].text + "\n";
   }

}
alert(myElements);
}

Note that the type of the element effects the way we need to access the value inside. Radio buttons and check boxes use ".checked" to determine if the value is either "true" or "false". The "name" of a select option is "select-one" (the single option version) and selected option is even more obscure as it is accessed by the "selectedIndex" array of the "options" elements. The select option therefore has yet one more lower array!

The Fundamental Form: When we build a form, we need to keep our audience in mind. It is usually a good policy to request only necessary information from a user, who may think twice if asked too many questions on a form. Since we are going with the assumption most of our form fields are REQUIRED to have some sort of user input, our most fundamental form will feature a form array looping structure to check that SOME data has been entered in each text box on a form, and will stop form submission and request further data from the user for each empty form element:

function checkForm(thisForm){ //this was used inside form, can be passed to function
   for(x=0; x<thisForm.length; x++)
   {
   if(thisForm.elements[x].value=="")
      {
      alert("Please enter required field: " + thisForm.elements[x].name); //show user we need input
      thisForm.elements[x].focus(); //focus the cursor in the textbox that was not filled in
      return false; //return a "false" to the form, telling it not to submit
      }
   }
return true; //if passed all checks, submit form
}

We send the entire form into the function, and can loop through all the elements of the form with the "length" property of the form. Each form element is a new item in the form element array. If any "value" is empty, we show the user an alert box, requesting data be inserted in the specific text box on the form. We access the element and use the "focus()" method to put the cursor into the text box for user convenience.

The "return false" indicates to the form NOT to submit! If all elements pass the test, the code falls to the "return true" statement, which tells the form to go ahead and submit the data. The "onSubmit" event is targeted in the form element in this manner:

<form name="myForm" action="myformhandler.asp" onSubmit="return checkForm(this);">

The keyword "this" can be used while inside the form tag itself to refer to the current form. You may remember the control word "this" also being used to access a current object, which in this case, the form is! Example: Simple Check Form

Checking for Specific Data: While the above example gets us started by seeing a user has entered some data, we often wish to limit the type of data a user may input. The easiest way to do this does not involve checking form data. If we know a user needs to input the State they live in, for example, we may elect to put all the states into a select option, to eliminate the possibility of typographical errors. However, we can't do this for all data, for example, an email address. For input where the user has "free form" access to enter data, we may elect to validate the value inside the form element. The following function checks a value for some of the string characteristics of an email address:

function checkEmail(eObj)
   { //checks for @ symbol and period only
   if(eObj.value.indexOf("@") != -1 && eObj.value.indexOf(".") != -1)
      {
      return true; //if "@" and "." are found, submit form

      }else{
      alert("Please enter a valid email address.);
      eObj.value = ""; //removes faulty email address
      eObj.focus();
      return false;
      }
   }

This example only checks for the presence of at least one "@" character, and one "." (period) character. It uses the "indexOf" string function, which normally returns a number indicating the location in the string of the requested substring. However, if the string DOES NOT exist, it returns -1, which is what we are using to determine if the characters exist in the email address. In this example, "eObj" refers to the form element that is being passed into the function, not the entire form. The form tag for this function would look like this:

<form name="myForm" action="myformhandler.asp" onSubmit="return checkEmail(this.Email);">

"this.Email" uses the control word "this" again to access the form, but adds the name of text box element, "Email" to send the text box element itself. Note also the faulty value is removed from the text box, prior to inserting the cursor back into the text box. Example: Simple Email Check

Screening For Illegal Characters: Another simple check might be to look for any illegal characters inside a form element:

function illChars(iObj){
var illegals = "!@#$%^&*()"; //a string of illegal chars, enter as many as you like!
var badChar = ""; //declare a var outside for loop
var myString = iObj.value; //pass the value to a string for easier reading code

 for(x=0; x<illegals.length; x++) //loop through all illegal characters
   {
      badChar = illegals.charAt(x); //copy current bad character to badChar for easier reading code
      if(myString.indexOf(badChar) != -1) //found a match, thats bad!
      {
      alert("You have entered an illegal character " + badChar);
      iObj.value = "";
      iObj.focus();
      return false;
      }
   }

return true;
}

You can enter as many "illegal" characters as you want into the variable "illegals" inside the function. If you wished to limit users to text input only, you could perhaps use the opposite logic, and limit a user to specific chars, instead. Here is the example for this page: Illegal Characters Check

 

Back To Top

 
2000, 2001, 2002 webdeavor, INC. & newmanic,   All rights reserved