JavaScript Primers #29

By Joe Burns

http://www.htmlgoodies.com/primers/jsp/article.php/3478421/JavaScript-Primers-29.htm (Back to article)

Use these to jump around or read it all


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment


The Concept

Our last JavaScript is a rough one, no doubt about it.

This example brings us back to forms. The program will use JavaScript to validate a user's data entry, which is often sloppy. In this example we will make the user enter a first name and we will require a zip code to be either 5 or 10 characters in length. We will also make sure that the first 5 characters are digits. This is a little more difficult than some, but hang in there. Data validation is an important issue for programmers.

This example re-introduces the length property. (Remember that a property is like an adjective. It describes a characteristic of an object.) This example shows us two new methods, indexOf(), charAt(). (Remember, methods are actions performed on objects. They always contain (parentheses).)

This program also shows you a longer function than you've seen before. You're ready now though, right? Right!


The Script

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
 function validfn(fnm)
  {
  fnlen=fnm.length
  if (fnlen == 0)
  {alert("First name is required")
  document.dataentry.fn.focus()}
  }
 function validZip(zip)
  {
   len=zip.length
   digits="0123456789"
   if(len != 5 && len != 10)
    {alert("Zip is not the correct length")
     document.dataentry.zip.focus()}

   for(i=0; i<5; i++)
   {if (digits.indexOf(zip.charAt(i))<0)
    {alert("First five digits must be numeric")
    document.dataentry.zip.focus()
    break}
      }
 
  }
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="dataentry">
 <h2>Form Field Validation</h2>

 Enter First Name:<br>
  <INPUT TYPE="text" NAME="fn" 
    onBlur="validfn(fn.value)">

<SCRIPT type="text/javascript">
  document.dataentry.fn.focus()
</SCRIPT>

     <p>

 Enter Zip Code (99999-9999):<br>
    <INPUT TYPE="text" NAME="zip" SIZE=10 >

    <P>

 <INPUT TYPE="button"  VALUE="Submit" 
     onClick="validZip(zip.value)">

</BODY>
</HTML>


The Script's Effect

Click here to open a new window demonstrating data entry validation.

Close the window to return to this document.


Deconstructing the Script


What You Have Learned


Your Assignment

First, get this program to run and study it. Then add one more piece to the validZip(zip) function that looks at position 5 to make sure it is a hyphen.

This "!=" means "is not equal" in JavaScript. You'll need that.

Here's a possible answer to this assignment
(this will open a new window)


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment

On To JavaScript Primer #30