The Wayback Machine - https://web.archive.org/web/20071012215631/http://webdeveloper.com:80/javascript/javascript_form_verification.html
WebDeveloper.com �: Where Web Developers and Designers Learn How to Build Web Sites, Program in Java and JavaScript, and More!   
Web Developer Resource Directory
Animated GIFs
CSS
CSS Properties
Database
Design
Flash
HTML
HTML 4.01 Tags
JavaScript
.NET
PHP
Reference
Security
Site Management
Video
XML/RSS
WD Forums
 Client-Side
  Development

    CSS
    Graphics
    HTML
    JavaScript
    XML
    Dreamweaver/FrontPage
    Multimedia
    Web Video
    General
    Accessibility

 Server-Side
  Development

    ASP
    Perl
    PHP
    .NET
    Java
    SQL
    Other

 Web Development
  Business Issues

    Business Matters
    Website Reviews

 E-Commerce
    Domain Names
    Search Engines

 Etc.
    Computer Issues
    Forum Software
    Feedback
    The Coffee Lounge



Script Downloads
Include CSS Stylesheet by DOM

Featured: October 12, 2007
Description: Use this script when you want to use the DOM to include a cascading style sheet. Very simple to implement.

Get Script

Hosting Search
Unix   Windows
PHP   Webmail

Sign up for the free WebDeveloper E-mail newsletter!


JupiterWeb Commerce
Partners & Affiliates
Partner With Us
Web Design
Mp3 Player Reviews
Laptop Batteries
Auto Insurance Quote
Promotional Products
Shop
Managed Hosting
Laptop Computers
Hurricane Shutters
Affiliate Programs
Imprinted Promotions
Cheap Plasma TVs
Domain registration
Promote Your Website

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

 eBook: The Mobile Explosion--This Isn't Your Father's Internet
Sponsored by Nokia
Every day, the Internet goes from being less of a luxury to more of a necessity for all of us. The worldwide growth of Internet usage combined with the nearly equal growth in mobile phone usage, more and more people will find the need to access the Internet through their mobile device. Learn how the mobile Web is evolving, the tips and tricks you'll need to go mobile, as well as the basics of what you need to get started on the mobile Internet. »
 
 eBook: Mobile Email and IM--A Strategic View
Sponsored by Nokia
This ebook examines the basics of what you need to know about workplace emails and instant messaging to help you understand what you're dealing with when you go mobile. It looks at the marketplace to show how mobile communications is poised to take off and discusses what you need to consider for implementing mobile email and IM in your enterprise. »
 
 How To: 7 Steps to Network Access Control
Sponsored by HP
Network access control helps ensure that only authorized users get access to the network. Furthermore, it ensures that users are granted access to only the network resources that they are authorized to use. Learn why it is essential that enterprises effectively administer network access depending on rights and needs.»
 
 Whitepaper: Secure File Transfer In the Era of Regulatory Compliance
Sponsored by Ipswitch
Increasing regulatory compliance mandates such as HIPAA, Sarbanes-Oxley, PCI DSS, BASEL II and J-SOX are compelling companies to establish a management strategy that includes the file transfer process. Learn how a Secure File Transfer approach can help companies meet the challenge of safely and reliably exchanging electronic business information. »
 

Client-Side Form Verification with JavaScript

by Heidi Brumbaugh

JavaScript code runs on the user's machine, making it an ideal method to perform simple verification on form data before submitting it on to the server. Performing the checks on the client side saves the user from waiting for the data to travel way back to the server, and then (if there's a problem) waiting again for an error message.

My original JavaScript tutorial showed you how to "grab" the onSubmit event from a form. Here we'll take that a step further, running our verification procedures before we decide whether to allow the data to be sent along.

I also showed you how to add a NAME field to an image tag, so that you could refer to that specific image later. Turns out JavaScript uses this NAME field in many HTML tags, including the FORM tag and the form fields' tags. Recall the hierarchical nature of JavaScript wants you to identify items first by document, then by form, then by field name. Separate each identifying level in the hierarchy with periods. For example, if you have a form defined like this:

<FORM name="Customer"> Your name: <INPUT type=text name="FirstLast" size=30 maxlength=75 value=""> </FORM>

You would access the customer's name field like this:

document.Customer.FirstLast.value

Okay, we know how to intercept the onSubmit event and how to examine the form fields. Next we'll use a few simple scripting commands to analyze the data. First, let's establish a variable, called valid, that we'll use to keep track of whether the data is valid. Initialize this value with 1 (meaning, to start out with, we'll assume everything is peachy).

var valid = 1

Now let's make sure the user entered something into the name and email fields of the form. This is fairly straightforward; if the field is blank, the form is invalid. In JavaScript, a double-equals sign checks for equality.

if (document.Customer.FirstLast.value == "") {
   valid = 0
}

We can verify the email address the same way.

Strings Are Things

Next let's add a more sophisticated check for the phone number. Since we might have long distance numbers or international numbers, we won't be too strict. But we will make sure the number falls with certain parameters: it contains only numerals, spaces, and the following characters: ( ) - +

To analyze the characters the user typed into the form field, you need to know about strings. In programming, a string is a sequence of alphanumeric characters. In JavaScript, most values that contain letters and numbers are string objects.

One way to think about strings is to imagine a sheet of grid paper. Each square on the page is numbered, starting with zero. When you create a string, you put one character in the first square, then next character in the second square, and so on. You can perform operations on the entire string, or you can use the grid numbers as an index into the individual elements of the string, giving you a convenient way to analyze the characters one by one.

Here are the JavaScript commands, including several string properties and methods, used in the phone number verification routine:

for (initial condition; end condition; increment command) { }
Performs an operation a certain number of times. We'll use an index into the string we want to analyze. Thus the initial condition is the index equals zero, the end condition is the index has reached the end of the string, and each time through the loop we'll increment the counter by one.

StringName.length
This property of a string object returns the number of characters in the string.

StringName.charAt(position)
This method returns the character at the index position. Remember the first character index is 0, the last is length-1. For example, MyName.charAt(0) returns "H" if MyName is "Heidi".

StringName.indexOf(SearchString)
This method returns the position of SearchString inside a string, or -1 if SearchString is not found. The verification routine makes up a string containing all the valid phone number characters. The indexOf method compares each character in the string with this list of numbers. If -1 is returned for any character, the phone number is invalid.

Here's the final routine:

function CheckPhoneNumber(TheNumber) {
	var valid = 1
	var GoodChars = "0123456789()-+ "
	var i = 0
	if (TheNumber=="") {
		// Return false if number is empty
		valid = 0
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {
// Note: Remove the comments from the following line to see this
// for loop in action.
// alert(TheNumber.charAt(i) + " is no good.")
			valid = 0
		} // End if statement
	} // End for loop
	return valid
}

One thing to note here is that valid is used in both CheckPhoneNumber and VerifyData. Because the variable is declared separately in each function (with the var statement), they are completely independent of each other. In programmerese, these variables are local. (In English, they are blissfully unaware of each other.)

Check out the complete example. There's a lot going on here, especially in the CheckPhoneNumber routine. To learn more about the commands used here, check out the syntax and examples at Netscape's JavaScript Reference. One thing you can do is to look up the String object, and see what other methods are available to you.




Acceptable Use Policy

JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info