SiteExperts.com Logo Home | Community | Developer's Paradise
User Groups | Site Tools | Site Information | Search
 Main Menu
 Resource

Form Validation Techniques

Categories...
Client User Group
HTML, CSS and XML, Internet Explorer
Language
JavaScript
Product
IE4, IE5
Task
Form Enhancement
Technology
Intrinsic Controls

Sponsored Links
Developer's Paradise : Inside Technique :
Form Validation Techniques
Submission by SiteExperts Staff

Go to the resource:
Form Validation Techniques

Add to Assistant

Short Description
We present three techniques (from the book Inside Dynamic HTML) for validating user input.

Long Description
One of the best uses of JavaScript is to validate user input. This article contains an excerpt from Scott Isaacs' book, Inside Dynamic HTML (Buy Now), explaining three techniques for validating user input. These techniques only work in Internet Explorer 4.0 and later as they rely on Microsoft's implementation of DHTML (except the state validation script that works cross-browser).

Author
Scott Isaacs
Date/ Version
8/29/1999
Submission URL
http://www.SiteExperts.com/tips/html/ts18/page1.asp
Submission Date
Aug 29,1999
Last Update
Aug 29,1999
 

Discussion and Rate this Resource
Overall Rating: 4

xz0002 on Aug 31, 2000 at 3:58:30 PMRating: 4
mxterplixer on Mar 18, 2000 at 9:40:02 AMRating: 5

Good article!  My thinking cap is tickle by articles like this one.  It may not be perfect, but it encourages other to continue finding better solutions.

We combined some of the solutions and came up with this validation for Text and Empty fields while typing in the fields and at form submition:

<STYLE TYPE="text/css">

            .badValue {background:red; color:white}

            .goodValue {background:white; color:black}

</STYLE>

<SCRIPT LANGUAGE="JavaScript">

   function validateEmpty() {

      // Get the source element.

      var el = event.srcElement;

      // Valid not empty

      var num = " ";

      event.returnValue = false;

      /* Loop over contents. If the field is empty,

         set the return value to false. */

      for (var intLoop = 0;

         intLoop < el.value.length; intLoop++)

         if (-1 == num.indexOf(el.value.charAt(intLoop)))

             event.returnValue=true;

                           if (!event.returnValue)       // Bad value

           el.className = "badValue"; // Change class to badValue.

                   else

           // Change class to goodValue.

           el.className="goodValue";

   }

 

         function isEmpty(str) {

            // Check whether string is empty.

            for (var intLoop = 0; intLoop < str.length; intLoop++)

               if (" " != str.charAt(intLoop))

                  return false;

            return true;

         }

 

         function checkRequired(f) {

            var strError = "";

            for (var intLoop = 0; intLoop<f.elements.length; intLoop++)

               if (null!=f.elements[intLoop].getAttribute("required"))

                  if (isEmpty(f.elements[intLoop].value))

                     strError += "  " + f.elements[intLoop].name + "\n";

            if ("" != strError) {

               alert("Required data is missing:\n" + strError);

               return false;

            }

         }

</SCRIPT>

<form method="post" ACTION="action " ONSUBMIT="return checkRequired(this);">

<input type="text" name="realname" size="50" maxlength="50" ONCHANGE="validateEmpty();" required>

&nbsp;<font color="RED" face="Arial" align="bottom">[Required]</font>

and so forth…
biedron on Mar 16, 2000 at 9:17:34 AMRating: 2

I've created this function for checking input while user types :

function thcKeyCheck(all,evnt,ignoreCase) {                  
 if(document.all)
  t=String.fromCharCode(evnt.keyCode);
 else
  t=String.fromCharCode(evnt.which);
 if(ignoreCase) {
  t = t.toLowerCase();all = all.toLowerCase();
 }
 if (all.indexOf(t)!=-1)
  return true;
 else
  return false;
}
It should be used as follows

<input type="text" onKeyPress="return thcKeyCheck('1234567890',event);
or
onKeyPress="return thcKeyCheck('abcdefghijklmo',event,true);

'true' makes the check case insensitive. This function works in NS4 and IE4+

adsmart on Mar 13, 2000 at 4:41:23 PMRating: 3

Doing validation in this manner is a really lowbrow way to doing things. Modern versions of both IE and Netscape support Regular expressions which are a far more robust way of doing most things. For instance, if you want to validate an email address, you can make them sufficiently robust that you can guarantee a reasonably formatted address is sent.

Try this code

 var checkStr = theForm.email.value;    // The value to check
  var regEmail = /^[A-Za-z0-9\-_]+(\.[A-Za-z0-9\-_]+)*@([A-Za-z0-9\-_\.]+\.)+[A-Za-z]{2,3}$/i
  if (checkStr.search(regEmail) == -1)
  {
    alert("Please enter a valid email address.\nIf your email address conatains \ncharacters other than letters, \nnumbers, - or _ please email us.");
    theForm.EMail.focus();
    return (false);
  }

Check out Netscape's article on this for more details: Form Validation with JavaScript 1.2 Regular Expressions for a good place to start. IMHO, they don't always have the best expressions but you can probably find better ones

hugo on Dec 8, 1999 at 1:40:40 PMRating: 5
Good program , very quick fonctionnality bravo !
jsheld on Dec 3, 1999 at 12:28:01 PMRating: 2
The first method - capturing characters via the ONKEYPRESS event handler - is IE-specific. Developers continue to pull their hair out because of the differences, so it is extremely important to note which solutions work for which browsers. While all work for IE, only #2 does for netscape. You should include this information!

More Ratings/ Comments


To rate and comment on a resource, you must first logon.

If you are not registered, please register yourself to become a member of the SiteExperts.community.

User Name
Password

Copyright © 1997-2008 InsideDHTML.com, LLC. All rights reserved.