EzBlog

Blogs from the mind of Tim Price

My Links

Blog Stats

Article Categories

Archives

Client Side Validation

Client-Side JavaScript Form Validation

This blog will illustrate exactly how to use client side JavaScript to validate user input in a completely reusable form, by including a JavaScript source file in every web page that needs it validation. The JavaScript will be written in such a way that it doesn’t need to know in advance the actual content of the form. This will allow you to write the routine once and include it in whichever form requires validation. To do this simply create a new text file, write your JavaScript and save it with a .js extension. This newly created file can then be included in whichever page requires the form validation routine.

Let’s have a look at the JavaScript required to validate any web form. This first function simply returns true if the given string contains only white space characters or false if not.

 

function isWhiteSpace(sString){

      for(var i = 0; i < sString.length; i++){

            var sChar = sString.charAt(i);

            if((sChar != ‘ ‘) && (sChar != ‘\n’) && (sChar != ‘\t’)) return false;

      }

return true;

}

 

This is the main function that is used to perform the validation. This function is called by the onSubmit() event handler.

 

function verify(oForm){

      var sMessage;

      var emptyFields = '';

      var sErrors = '';

 

      for(var i = 0; i < oForm.length; i++){

            var oElement = oForm.elements[i];

            if (((oElement.type == "text") || (oElement.type == "textarea")) && !oElement.optional){

                  if((oElement.value == null) || (oElement.value == '') || isWhiteSpace(oElement.value)){

                        emptyFields += "\n\t" + oElement.name;

                        continue;

                  }

 

                  if(oElement.numeric || (oElement.minimum != null) || (oElement.maximum != null)){

                        var iValue = parseFloat(oElement.value);

                        if (isNaN(iValue) ||

                              ((oElement.minimum != null) && (iValue < oElement.minimum)) ||

                              ((oElement.maximum != null) && (iValue > oElement.maximum))){

                              sErrors += " The field " + oElement.name + " must be a number";

                              if (oElement.minimum != null)

                                    sErrors += " that is greater than " + oElement.minimum;

                              if (oElement.maximum != null && oElement.minimum != null)

                                    sErrors += " and less than " + oElement.maximum;

                              else if (oElement.maximum != null)

                                    sErrors += " that is less than " + oElement.maximum;

                                    sErrors += ".\n";

                        }

 

                  }

            }

            else if(oElement.type == "checkbox" && !oElement.optional){

                  if (!oElement.checked){

                        emptyFields += "\n\t" + oElement.name;

                        continue;

                  }

            }

            else if(oElement.type == "select-one" && !oElement.optional){

                  if (oElement.options[oElement.selectedIndex].value == "0" ||

                        oElement.options[oElement.selectedIndex].value == ''){

                              emptyFields += "\n\t" + oElement.name;

                              continue;

                        }

            }

            else if(oElement.type == "select-multiple" && !oElement.optional){

                  var iSelected = 0;

                  for(var i = 0; i < oElement.options.length; i++){

                        if(oElement.options[i].selected){

                              iSelected ++;

                              continue;

                        }

                  }

                  if (iSelected == 0){

                        emptyFields += "\n\t" + oElement.name;

                        continue;

                  }

            }

      }

      if(!emptyFields && !sErrors) return true;

      sMessage = "The form was not submitted because of the following error/s.\n";

      sMessage += "You will need to correct this and submit the form again!\n\n";

 

      if(emptyFields){

            sMessage += "The following fields are required:" + emptyFields + "\n";

            if(sErrors)sMessage += "\n";

      }

      sMessage += sErrors;

      alert(sMessage);

      return false;

}

 

The first part of this function loops through all the elements in the forms elements collection, looking for all the text, textareas, checkboxes and select elements. Whilst checking the type of the element we are also checking to see whether the element has an ‘optional’ parameter declared. We then make a list of all the elements that are required but have not had a value entered. Also, if any of these elements have a minimum or maximum property set, then we ensure that they are numbers and within the right range.

 

Finally, if there are errors, we display the errors in an alert and return false to the calling event handler. Otherwise we return true. Depending upon the return value if this function will determine whether or not, the form is submitted.

 

Don’t forget that this code is in fact in an included script file, defined within the section of our HTML.

 

Below is an example of a form that uses our verify function. As you will see verify is called from the onSubmit() event handler for the form, and return whatever value the function returns. It is also, within the onSubmit() event that we also set the properties of the form objects that the verify function needs to verify.

 

this.MailingList.optional = false;

this.Firstname.optional = false;

this.Phone.optional = true;

this.Age.minimum = 18;

this.Age.maximum = 40;

this.Hobbies.optional = false;

            return verify(this);

">

 

First Name:

Last Name:

Phone:

Age:

Hobbies:

 

 

 

There you have it.

posted on Thursday, September 02, 2004 10:43 AM