spacer
home / programming / javascript / jf / column9 / 1 current pageTo page 2
[next]

Web Project Manager
Aquent
US-PA-Collegeville

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

JavaScript and Accessibility. Pt. 2.

By Jonathan Fenocchi

Last week we began this series with a discussion about new practical and standards-compliant use of JavaScript. In part one of this series, we covered how functionality and usability will be the primary concerns of JavaScript in 2005. We introduced Web Standards, what they mean to the developer, introduced the reader to responsible scripting, and began a discussion concerning classical techniques and how to fix them. We continue that this week beginning with Form Validation. [Ed. note.]

Form Validation

Another classical idea is form validation. Here’s an example:

The Script.
<script type=”text/javascript”><!—
  function validateForm(){
    if(myForm.fName == "" || myForm.lName == "" || myForm.fColor == ""){
      alert("Please fill in all fields.");
    return false;
  }
 return true;
}
//--></script>

The HTML.
<form name="myForm" action="some-script.pl" method="post" onsubmit="return validateForm()"><fieldset>
<legend>Enter your information</legend>
<label>First name: <input type="text" name="fName"></label><br>
<label>Last name: <input type="text" name="lName"></label><br>
<label>Favorite color: <input type="text" name="fColor"></label><br>
<label><input type="submit" value="Submit form"></label>
</fieldset></form>

This script may work in some cases, but it has a few flaws. The form, named “myForm,” is referenced in the global scope. This is wrong because “myForm” could also be a variable. It is also incorrect to use document.all[“myForm”] since, according to the W3C specifications, there is no such thing as “document.all.” The script is unlikely to work in most browsers, and sure to fail in archaic ones. Another problem is that you could enter a space in any of the fields and the script would assume it is valid. You may already know, but for clarification, the “return” part of our code in the onSubmit event is to prevent the form from submitting if the validation fails. This is also why “return true” and “return false” statements are included in the function. When a function reaches a “return” statement, it ends the function, even if code follows thereafter. Also, you should take note that Regular Expressions should be used for any sort of string validation – in JavaScript or in any other programming language that makes it available. Since the HTML is perfectly fine in this instance (validation should also be done on the server-side for users who have JavaScript disabled) we only need to update the JavaScript itself.

<script type="text/javascript"><!--
  function validateForm(){
    var theForm = document.forms["myForm"];
    var regex = /^\s*$/i;
      if(regex.test(theForm.fName.value) || regex.test(theForm.lName.value) || regex.test(theForm.fColor.value)){
alert("Please fill in all fields.");
       return false;
    }
  return true;
}
//--></script>

Notice that we set the variable “theForm” to document.forms[“myForm”]. This is the proper way to point to the form named “myForm.” Since this is the first form of the document, you can also refer to it as “document.forms[0].” We set a separate variable, “regex,” to hold our regular expression. This isn’t entirely important, but it saves a little memory – you can just refer to a variable instead of typing out the RegEx each time you run a match against an element’s value to validate it. In a human-readable format, you could say that this RegEx says that it will match “anything that begins and ends with zero or more spaces.” If the text field is empty or has only whitespace in it, the RegEx will match it and the function will return false.

Instead of setting the variable “theForm” to a form element that we know exists, we can write a sort of global form validation function, which we can use on any form. Then we can include it in an external *.js file to be cached by the browser and quickly available whenever we need it. We’ll need to make just a tiny modification to our FORM element, so that no matter what the name of the FORM is, we can still validate it.

<form name="myForm" action="some-script.pl" method="post" onsubmit="return
validateForm(this)">

By adding “this” we can send the FORM object to the validateForm function.

<script type="text/javascript"><!--
  function validateForm(f){
    var regex = /^\s*$/i;
      for(var i=0; i<f.elements.length; i++){
        if(regex.test(f.elements[i].value)){
          alert("Please fill in all fields.");
          f.elements[i].focus();
          return false;
       }
    }
  return true;
}
//--></script>

Since we passed “this” to the function, the local variable “f” now refers to the FORM element and all its properties. Therefore, we can run a for loop through the array of elements and test them for validity. All of the elements are being checked to make sure they are not empty, so we have no problem.

If we wanted to test for numbers or letters exclusively, we modify the form and add a CLASS attribute that will tell us what kind of validation should be done on each particular element. This gives us control of the appearance of elements that require different validation methods.

Note: You can color the borders of all the form elements that are numbers only red by changing the CSS accordingly. This is optional for the CSS, but required for the JavaScript. Replacing the field for your favorite color with a field for your age, we get the following form:

<form name="myForm" action="some-script.pl" method="post" onsubmit="return validateForm(this)"><fieldset>
<legend>Enter your information</legend>
<label>First name: <input type="text" name="fName" class="letOnly"></label><br>
<label>Last name: <input type="text" name="lName" class="letOnly"></label><br>
<label>Age: <input type="text" name="age" class="numOnly"></label><br>
<label><input type="submit" value="Submit form"></label>
</fieldset></form>

 

home / programming / javascript / jf / column9 / 1 current pageTo page 2
[next]

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Symantec Whitepaper: Converging System and Data Protection for Complete Disaster Recovery
Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
  Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Symantec Whitepaper: Comprehensive Backup and Recovery of VMware Virtual Infrastructure
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Fixing MySQL Replication · Firewall Guide: First Steps to Securing the Enterprise · VoxOx Tames the Tumultuous Communications Tangle

Created: March 27, 2003
Revised: February 21, 2005

URL: http://webreference.com/programming/javascript/Jf/column9/1