SHARE
Facebook X Pinterest WhatsApp

JavaScript Primers #29

Written By
thumbnail
Joe Burns
Joe Burns
Jan 4, 2005

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


  • The script is quote basic. There are two functions, validfn() and validzip(). One checks the text box for the first name, the other checks the box for the zip code. Let’s look at the first name validator function first.
    function validfn(fnm)
     {
      fnlen=fnm.length
      if (fnlen == 0)
       {alert("First name is required")
        document.dataentry.fn.focus()}
      } 
      .....
      <body>
      .....
    
    <INPUT TYPE="text" NAME="fn" 
       onBlur="validfn(fn.value)">
    
    
  • The function validfn(fnm) is called by the onBlur event. onBlur occurs when the focus moves away from a field, in this case the text field fn. We went over onBlur way back in the Event Handler Primer.
  • Notice that the argument fn.value is passed from the form to the function where it is renamed fnm. fn.value could have been referenced as document.dataentry.fn.value, but since we are in the document and also inside the form, this is unnecessary.
  • Remember that to see the contents of a form field we need to use field name.value. You must add that “value” to see the contents. The name alone won’t do it.
  • A variable called fnlen is assigned the value of the length of the first name. Thus if the first name is “Joe”, the
    value of fnlen will be 3. Remember the length property?
  • If the length is 0, then the user has not typed in a first name. The program then gives the user an error message and puts
    the focus or pointer in the first name field. The form is not so much checking to see if a correct name has been typed in, rather it’s checking if anything has been typed in.

  • Now, let’s look at the validation for the zip code:
  • 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}
      }
    

  • This is a longer function. Let’s examine it one piece at a time. The first piece sets the variable len to the length of the zip code. A variable called digits is given the value of all digit values.
  • The If statement then tests to see if the length of zip is not equal to 5 and not equal to 10. This sounds a little awkward, but that’s what it’s doing. The double && means for the JavaScript to check both properties.
  • If this is true, then it tells the user that the first five digits must be numeric and sets the focus or pointer to the
    zip field.
  • for(i=0; i<5; i++) looks at the first five digits of the zip code, one at a time.
  • if (digits.indexOf(zip.charAt(i))<0) introduces the methods indexOf(0 and charAt(0.
  • Let’s look at zip.charAt(i). Suppose the zip code is 123, and i is 2. The character at position 2 is the number 3. This
    is not a typo, index numbers begin with 0! Thus zip.charAt(0) is 1 and zip.charAt(1) is 2!
  • indexOf is a method that returns the index number of a given value. With if (digits.indexOf(zip.charAt(i))<0),
    JavaScript searches for the character in zip.charAt(0i in the digits variable. If the zip code is 12345 and i is 1, the program looks for 2 in the digits variable, and finds it, returning the value 2 as digits is “0123456789”.
  • If the zip code is “01b” and i is 2, the program looks for b in the digits variable. When it does not find this, it returns a -1. If the value is -1, then an error message is given and the focus or pointer is set to the zip field.

  • And last but not least, here’s the HTML text that creates the form items:

    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)”>


  • When you use forms with JavaScript, each form item must be given a name that links it to the sections of the JavaScript that will act upon it. You’ve seen this type of linking a couple of times before.

    Look over the form items and then the JavaScript and find where one links to the other. It should all be starting to make sense by now.



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

Recommended for you...

The Revolutionary ES6 Rest and Spread Operators
Rob Gravelle
Aug 23, 2022
Ahead of Time (AOT) Compilation in Angular
Tariq Siddiqui
Aug 16, 2022
Converting a JavaScript Object to a String
Rob Gravelle
Aug 14, 2022
Understanding Primitive Type Coercion in JavaScript
Rob Gravelle
Jul 28, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.