DevNewz Home PageAbout iEntryArticle ArchiveNewsWebProWorld ForumsJaydeiEntryContactAdvertiseDownloadsiEntry
^ click above ^
05.04.04


HTML Forms Validation On The Client Side

By Martin Tsachev

Form validation on the client-side is essential - it saves time and bandwidth; you also have better control to show the user the wrong field. This comparison of different validation methods includes comments for improving portability and maintainability.

Why is Client Side Validation Good

  • It is fast, if something is wrong the alarm is triggered upon submission of the form
  • You can safely display only one error at a time and focus on the wrong field

Two Major Validation Approaches

  • Display the errors one by one, focusing on the offending field
  • Display all errors, server-side validation style

While displaying all errors is needed in case of server validation, the better method for client validation is to show one error at a time. This makes it possible to highlight the wrong field, making it a lot easier for the visitor. If you print all errors most people would also try to remember and correct them at once instead of trying to submit after each correction.

Considering these advantages I will focus only on validation methods that display one error at a time.

How to Validate Forms

Take for example the following code fragment:

<script type="text/javascript" language="javascript">
function validateMyForm() {
     if (parseInt(document.forms[0].phone.value) !=
    document.forms[0].phone.value) {
         alert('Please enter a phone number, numbers only');
         return false;
     }

     return true;
}
</script>

<form action="handler" onsubmit="return validateMyForm();">
     <p>Phone: <input type="text" id="phone" name="phone" /></p>

     <p><input type="submit" value="Send" /></p>
</form>


So what's wrong: If you add another form before this one the code will try to validate the wrong one.

Note: JavaScript is case sensitive, the value which is assigned to the HTML id/name attribute is also case sensitive.

A better approach would be to add a form name:

function validateMyForm() {
    if (parseInt(document.forms.myForm.phone.value) !=
   document.forms.myForm.phone.value) {

<form id="myForm" name="myForm" action="handler"
  onsubmit="return validateMyForm();">


This is definitely better but still not portable enough - if you want to reuse some of the validation for another form you will have to do a lot of text replacing.

Let's remove the form name:

function validateMyForm(form) {
    if (parseInt(form.phone.value) != form.phone.value) {

<form action="handler"
  onsubmit="return validateMyForm(this);">


The last method makes use of the this object which always points to the current object, making our code more portable and saving keystrokes.

Now how about making visitors' lives a lot easier and focus the field that triggered the error instead of making them find it on their own.

function validateMyForm(form) {
     if (parseInt(form.phone.value) != form.phone.value) {
          alert('Please enter a phone number, numbers only');
          form.phone.focus();
          form.phone.select();
          return false;
   }


With these changes the browser will focus the wrong field and even select the text for the visitor, if scrolling is needed it will also happen automatically.

That was pretty good, but don't you feel that it's a little too much code for every single field? If we create a simple library of functions we can save lots of typing and download time for the page.

Well next we'll do exactly this and define our basic functions that make validation code even shorter.

function validateNumber(field, msg, min, max) {
     if (!min) { min = 0 }
     if (!max) { max = 255 }

     if ( (parseInt(field.value) != field.value) ||
   field.value.length < min ||
   field.value.length > max) {
         alert(msg);
         field.focus();
         field.select();
         return false;
     }

     return true;

}
This function does a simple validation of a number - it checks whether the field contains digits only, and optionally if it is within a given range.

We are passing the error message as a parameter to it, to use such a function we can basicly add it to the onsubmit handler like:

<form action="handler"
    onsubmit="return validateNumber(this.phone,
   'Please enter a phone number, digits only', 5, 10);">


Read the rest of this article here.


About the Author:
Martin Tsachev has been developing for the web since 2001. He's currently working as a web developer at Make-a-Store, Inc.. Martin's personal site mtWeb can be found at martin.f2o.org.

Read this newsletter at: http://www.devnewz.com/2004/0504.html
Free Newsletters
Part of the iEntry Network
over 4 million subscribers
DevNewz
ITProNews
MacProNews


Send me relevant info on products and services.


 

 

From the Forum:
change statement

I need to choose option from a list bar. after choose an option, it will automatically show at below replacing the null. when the statement is display, I can change it to replace with the more updated one. Then click submit button when property description is changed. the problem is my program can't automatically display statement when I choose option from list bar. I include some part of my code and hope to be corrected. I am using jsp ...

Go Here

 

 
Have your listing reach beyond the saturated portals and search engine destination sites into the Internet's best content sites ->learn more
 

 

 

-- DevNewz is an iEntry, Inc. publication --
iEntry, Inc. 880 Corporate Drive, Lexington, KY 40503
2004 iEntry, Inc.  All Rights Reserved  Privacy Policy  Legal

archives | advertising info | news headlines | free newsletters | comments/feedback | submit article



DesignNewz.com DevWebPro.com