[thelist] JS Form Validation

Joshua Olson joshua at waetech.com
Fri Jul 2 14:16:25 CDT 2004


> -----Original Message-----
> From: Joshua Hmielowski
> Sent: Friday, July 02, 2004 2:35 PM
>
> The Function...
>
> function validate() {
>      if (document.myForm.realname.value == '') {
>         alert('Please complete the First Name field');
>          document.myForm.realname.focus();
>           return false; }
>
>    else if (document.myForm.lastname.value == '') {
>          alert('Please complete the Last Name field');
>          document.myForm.lastname.focus();
>           return false; }
>
>          else
>          document.myForm.action = "mailto.php";
>          return true; }

Joshua,

Good work.  Here are some pointers that will make the code even simpler.

1.  Change the form tag to the following:

<form name="myForm" method="post"  action="mailto.php" onsubmit="return
validate(this);">

2.  Then, use the form reference passed to the function to simplify the
code:

function validate(form) {
     if (form.elements.realname.value == '') {
        alert('Please complete the First Name field');
         form.elements.realname.focus();
          return false; }
   if (form.elements.lastname.value == '') {
         alert('Please complete the Last Name field');
         form.elements.lastname.focus();
          return false; }

    return true;
}

3.  My Rule Of Thumb #1.  Always reference form elements through the form's
elements collection.  The above code reflects this change.  This is
important for cases when form elements may be named the same as attributes
of the form tag.

4.  My Rule Of Thumb #2.  Always have a valid "action" attribute, ESPECIALLY
if the target page is not the current page.  Do not rely on the value being
set via JS.

5.  My Rule Of Thumb #3.  If you do want to programmatically change the
attributes of the form tag, use the attributes collection.  Example:
myform.attributes.action = 'mailto.php';

Form validation via JS isn't really quirky at all across various browsers so
long as some of the best practices are employed.  So long as you stay away
from the DOM shortcuts, then you should be okay in nearly all cases.  For
example, the proper way to examine the selected value of a dropdown is as
follows:

myselect.options[myselect.options.selectedIndex].value

But some browsers allows for this:

myselect.value

Stick with the former option and rest assured your code will work on most,
if not all, JS enabled browsers.

A great deal many of the JS examples you'll find out there do things "the
wrong way" and may have compatibility.  If you have questions about examples
you find, do not hesitate to ask thelist, or me directly.

Best of luck,

<><><><><><><><><><>
Joshua Olson
Web Application Engineer
WAE Tech Inc.
http://www.waetech.com/service_areas/
706.210.0168




More information about the thelist mailing list