13.4 Form Validation with Regular Expressions


When you fill out a form on the Web, you are typically asked for your name , phone, address (a pop-up menu of all the states is usually provided), and then all sorts of credit card stuff. Sometimes it takes four or five tries to get it right because you didn't complete the form exactly the way you were asked. A message will appear and you won't be allowed to submit the form until you get it right. Behind the scenes a JavaScript program is validating the form.

13.4.1 Checking for Empty Fields

There's a form waiting to be filled out. Some of the fields are optional, and some are mandatory. The question is, did the user fill in the mandatory fields? If he didn't, the form can't be processed properly. Checking for empty or null fields is one of the first things you may want to check.

Example 13.36
 <html>     <head>     <title>Checking for Empty Fields</title>     <script language="JavaScript"> 1  function validate_text(form1)  { 2      if (  form1.user_name.value == ""  form1.user_name.value  ==   null  ){           alert("You must enter your name.");  return false;  } 3      if (  form1.user_phone.value == ""  form1.user_phone.value ==   null  ){           alert("You must enter your phone.");  return false;  }        else { 4  return true;  }     }     </script>     </head>     <hr>     <body>     <h2> Checking for Empty fields </h2> 5  <form name="formtest" action="/cgi-bin/form1.cgi" method="get"   onSubmit="return validate_text(formtest)">  Please enter your name: <br> 6   <input type="text" size=50 name="user_name">     <p>     Please enter your phone number: <BR> 7   <input type="text" size=30 name="user_phone">     <p>  <input type=submit value="Send">  <input type=reset value="Clear">     </form>     </html> 

EXPLANATION

  1. A user-defined function called validate_text() is defined. It takes one parameter, a reference to a form.

  2. If the value in the first text field is an empty string (represents a string with no text) or null (represents no value), the user is sent an alert asking him to fill in his name. If a false value is returned, the form is not submitted.

  3. If the value in the second text field is an empty string or null, the user is sent an alert asking him to fill in his phone. If a false value is returned, the form is not submitted.

  4. If both text boxes were filled out, a true value is returned, and the form will be submitted to the server's CGI program whose URL is listed in the action attribute of the form.

  5. The onSubmit event is triggered when the user presses the submit button. The handler function, validate_text() , will be called with a reference to this form.

  6. The input type for this form is a text box that will get the name of the user.

  7. Another text box is created to hold the phone number of the user. See Figure 13.36.

    Figure 13.36. The user left the phone field empty, so the form was not submitted.

    graphics/13fig36.jpg

13.4.2 Checking for Numeric Zip Codes

If you ask the user for a five-digit zip code, it is easy to check using a regular expression by matching for exactly five digits:

 
 /^\d{5}$/ 

Another way to say the same thing:

 
 /^[0-9][0-9][0-9][0-9][0-9]$/ 

Some longer zip codes contain a dash followed by four numbers . This long zip code format could be represented as:

 
 /^\d{5}-?\d{4}$/ 

The beginning and end of line anchors prevent the matched string from containing any extraneous characters at either end of the string. See Example 13.37.

Example 13.37
 <html>     <head><title>Testing for a Valid Zip Code</title>     <script language="JavaScript"> 1  function ok_Zip(zip){  2      var regex=  /^\d{5}$/  ;  //  Match for 5 numbers  3      if (regex.test(zip.value) == false) {           alert("Zip code must contain exactly five numbers!");           zip.focus();           return false;        } 4      if (zip.value == ""){           alert("You must enter a zip code");           zip.focus();           return false;        }           return true;     }     </script></head>     <body><font face="arial" size="+1">     <form name="ZipTest" action="/error" >     Enter your zip code:     <input type="text"        name="zipcode"        size=5>     <input type="button"        value="Check zip" 5  onClick="if(ok_Zip(ZipTest.zipcode)) {alert('Zip is   valid.')}">  <br><input type="reset">  </form>  </body>     </html> 

EXPLANATION

  1. The function, called ok_Zip() , is defined to validate the zip code entered by the user.

  2. The regular expression reads: Look for exactly five digits. The beginning of line and end of line anchors ensure that there will not be any extraneous characters before or after the five digits.

  3. The regular expression test() method checks that the value entered by the user is a valid zip code. If not, an alert dialog box will tell the user, focus will returned to the text box, and false will be returned.

  4. If the user doesn't enter anything, an alert dialog box will appear, focus will be returned to the text box, and false will be returned.

  5. The onClick event is triggered when the user clicks the "Check zip" button. A JavaScript statement to call the ok_Zip() function is assigned to the event. If the user entered a valid zip code, the alert dialog box will pop up and say so. See Figure 13.37.

    Figure 13.37. The user enters a five-digit zip code (top); the user enters nothing (middle); the user enters 4 digits and 1 letter (bottom).

    graphics/13fig37.jpg

13.4.3 Checking for Alphabetic Data

To test for entries that must consist strictly of alphabetic input, such as a name, state, or country field, the regular expression character set can be used; for example, /[a-zA-z]+/ is a regular expression that matches a string containing one or more uppercase or lowercase letters , and /^[a-zA-Z]+$/ matches a string containing only one or more uppercase or lowercase letters, because the character set is enclosed within the beginning and ending anchor metacharacters. To represent one or more alphanumeric word characters, [A-Za-z0-9_], you can use the \w metasymbol; for example, /\w+/ represents one or more alphanumeric word characters.

Example 13.38
 <html>     <head><title>Testing for Alphabetic Characters</title>     <script language="JavaScript"> 1  function okAlpha(form)  { 2  var regex=/^[a-zA-Z]+$/;  //  Match for upper- or lowercase letters  if (regex.test(form.fname.value) == false) {           alert("First name must contain alphabetic characters!");           form.fname.focus();           return false;        } 3      if (form.fname.value == ""){           alert("You must enter your first name.");           form.fname.focus();           return false;        } 4      return true;     }     </script>     </head>     <body><font face="arial" size="+1"> 5  <form name="alphaTest"  method="post"        action="/cgi-bin/testing.pl" 6  onSubmit="return okAlpha(this)" >  Enter your first name:        <input type="text" 7  name="fname"  size=20>        <p> 8      <input type="submit" value="Submit">        <input type="reset">     </form>     </body>     </html> 

EXPLANATION

  1. A function called okAlpha() is defined. It takes one parameter, a reference to a form. Its purpose is to make sure the user entered only alphabetic characters in the form.

  2. A regular expression is created. It reads: Starting at the beginning of the line, find one or more uppercase or lowercase letters in the character class [A-Za-z] followed by the end of line anchor ( $ ). The regular expression is tested against the input that came in from a text box named text . If it doesn't match, the alert box will notify the user, and false is returned to the onSubmit handler on line 6. The form will not be submitted.

  3. If the user didn't enter anything at all and the field is empty, another alert will be sent to the user, and false will be returned. The form will not be submitted.

  4. If the user entered only alphabetic characters in his name, true will be returned, and the form will be submitted.

  5. This is where the HTML form starts.

  6. The onSubmit handler will be triggered when the user presses the submit button, and the okAlpha() function will be called, passing a reference to the form called alphaTest .

  7. The user enters his name in the text field called fname .

  8. After filling out the form, the user will press the submit button, thereby triggering the onSubmit handler on line 6. See Figure 13.38.

    Figure 13.38. The user has a digit in his name. He can only enter alphabetic characters, or he will see the warning.

    graphics/13fig38.jpg

13.4.4 Removing Extraneous Characters

Removing Spaces and Dashes

To remove any unwanted spaces or dashes from user input, the String object's replace() method can be used to find the characters and replace them with nothing, as shown in Example 13.39.

Example 13.39
 <html>     <head>     <title>Removing Spaces and Dashes</title>     </head>     <body bgcolor="magenta">     <font size="+1" font face="arial">     <h2>Removing Spaces and Hyphens</h2>     <script language = "JavaScript"> 1  var string="444- 33 - 12 34"  2  var regex = /[ -]+/g;  3      var newString=  string.replace(regex, "");  document.write("The original string: "+string);        document.write("<br>The new string: "+ newString +"<br>");     </script>     </body>     </html> 

EXPLANATION

  1. The string contains numbers, spaces, and dashes.

  2. The variable called regex is assigned a regular expression, which means: Search for one or more spaces or dashes, globally (multiple occurrences within the string).

  3. The replace() method searches in the string for spaces and dashes, and if it finds any, replaces them with the empty string, "" , returning the resulting string to newString . To change the original string, the return value of the replace() method can be returned back to the original string: var string=string.replace(regex, "") ;

Figure 13.39. The replace() method is used to remove any spaces or dashes.

graphics/13fig39.jpg

Removing Unwanted Parentheses

You may also want to remove parentheses surrounding area codes or telephone numbers. This is a relatively simple regular expression used in the replace() method, as shown in next last example.

Example 13.40
 <html>     <head>     <title>Removing Parens</title>     </head>     <body bgcolor="magenta">     <font size="+1">     <font face="arial">     <h2>Removing Unwanted Parentheses, Spaces, and Dashes</h2>     <script language = "JavaScript"> 1  var string="(408)-332-1234"  2  var regex = /[() -]+/g;  3      var newString=string.  replace(regex, "");  document.write("The original string: "+string);        document.write("<br>The new string: "+ newString +"<br>");     </script>     </body>     </html> 

EXPLANATION

  1. The string contains numbers, parentheses, spaces, and dashes.

  2. The variable called regex is assigned a regular expression, which means: Search for one or more parens ( open or closed), spaces or dashes, globally (multiple occurrences within the string).

  3. The replace() method searches in the string for parens, spaces, and dashes, and if it finds any, replaces them with the empty string, "" , returning the resulting string to newString . To change the original string, the return value of the replace() method can be returned back to the original string: var string=string.replace(regex, "") ;

Figure 13.40. Parentheses, as well as spaces and dashes, are removed. Numbers or letters will remain .

graphics/13fig40.jpg

Removing any Non-Digits

A character that is not a digit can be represented as [^0-9] or as \D in a regular expression. You may want to remove any characters that are not digits in the user's input such as zip codes or phone numbers. This can also be done simply with a regular expression and the replace() method, as shown in the following example.

Example 13.41
 <html>     <head>     <title>Removing all Non-digits</title>     </head>     <body bgcolor="magenta">     <font size="+1" face="arial">     <h3>If it's not a number, remove it!</h2>     <script language = "JavaScript"> 1  var string="phone is (408)-//[332]-1234@#!!!"  2      var newString=  string.replace(/\D/g, "");  document.write("The orginal string: "+string); 3      document.write("<br>The new string: "+ newString +"<br>");     </script>     </body>     </html> 

EXPLANATION

  1. The string contains all kinds of characters, many which are not numbers.

  2. The replace() method searches in the string for all non-digit characters, /\D/g , and if it finds any, replaces them with the empty string, "" , returning the resulting string to newString . To change the original string, the return value of the replace() method can be returned back to the original string: var string=string.replace(regex, "") ;

  3. The new string is diplayed after all the non-digit characters were replaced with nothing; i.e., they were removed.

Figure 13.41. Only numbers will remain in the string. All other characters are removed.

graphics/13fig41.jpg

Removing any Non-Alphanumeric Characters

A non-alphanumeric word character [^0-9a-zA-Z_] , any character that is not a letter, number, or the underscore , can be represented as \W . Again we can use the replace() method to remove those characters from a string.

Example 13.42
 <html>     <head>     <title>Removing Non-Alphanumeric Characters</title>     </head>     <body bgcolor="magenta">     <font size="+1">     <font face="arial">     <h3>If it's not a number or a letter, remove it!</h2>     <script language = "JavaScript"> 1  var string="(408)-//[332]-1234@#!!!"  2      var newString=  string.replace(/\W/g, "");  3      document.write("The original string: "+string);        document.write("<br>The new string: "+ newString +"<br>");     </script>     </body>     </html> 

EXPLANATION

  1. The string contains all kinds of characters, many which are not letters or numbers.

  2. The regular expression, /\W/g , means: Search globally for any non-alphanumeric characters ( \W ). The replace() method searches for non-alphanumeric characters and replaces them with the empty string, "" , returning the resulting string to newString . To change the original string, the return value of the replace() method can be returned back to the original string: var string=string.replace(regex, "") ;

  3. The new string is diplayed after all non-alphanumeric characters are removed.

Figure 13.42. Any non-alphanumeric characters are removed.

graphics/13fig42.jpg

13.4.5 Checking for Valid Social Security Numbers

A Social Security number contains exactly nine numbers. There may be dashes to separate the first three numbers and the last four numbers. The dashes should be optional. Example 13.43 demonstrates a regular expression that tests for three digits, followed by an optional dash, followed by two more digits, an optional dash, and finally four digits. The beginning and end of line anchors ensure that the user does not enter extraneous characters on either end of his Social Security number, such as abd444-44-4444xyz .

Example 13.43
 <html>     <head><title>Testing for a Social Security Number</title>     <script language="JavaScript"> 1   function okSocial(sform){ 2  var regex=/^\d{3}-?\d\d-?\d{4}$/;  3       if (  regex.test(sform.ssn.value)  == false) {            alert("Social Security number invalid!");            sform.ssn.focus();            return false;         } 4       if (sform.ssn.value == ""){            alert("Please enter your Social Security number.");            sform.ssn.focus();            return false;         }         return true;     }     </script>     </head>     <body><font face="arial" size="+1">     <center>     <form name="snnTest"         method=post         action="/cgi-bin/testing" 5  onSubmit="return okSocial(this)" >  Enter your Social Security number: xxx-xx-xxxx     <p> 6   <input type="text"         name="ssn"         size=11>     <p> 7   <input type="submit" value="Submit">     <input type="reset">     </form>     </body>     </html> 

EXPLANATION

  1. The function okSocial() is defined. Its purpose is to validate a Social Security number.

  2. The regular expression reads: Start at the beginning of the line, look for three digits, one dash (or not one), two more digits, another possible dash, and ending in four digits.

  3. The regular expression test() method will return true if a valid Social Security number was entered and false , if not.

  4. If nothing was entered in the text box, the user will be alerted, focus will go to the text field, and the form will not be submitted.

  5. The onSubmit event handler will be triggered when the user presses the submit button, line 7.

  6. The input type is a text field that will hold up to 11 characters.

  7. When the user presses the submit button, the onSubmit event handler will be triggered. It will call the okSocial() function to validate the Social Security number. See Figure 13.43.

    Figure 13.43. User enters a valid Social Security number.

    graphics/13fig43.jpg

13.4.6 Checking for Valid Phone Numbers

A valid U.S. phone number has ten digits: an area code of three digits, followed by the subscriber number of seven digits. There may be parentheses surrounding the area code, and dashes or spaces separating the numbers in the subscriber number. With regular expressions you can test for any or all of these conditions and then, if necessary, remove the extraneous characters, leaving just numbers. Example 13.44 demonstrates how to validate a simple U.S. phone number.

Example 13.44
 <html><head><title>Validating Phone Numbers</title>     <script language="JavaScript">  function ok_Phone(phform){  1  var regex = /^\(?\d{3}\)?-?\s*\d{3}\s*-?\d{4}$/;  2  if(regex.test(phform.user_phone.value))  {             return true;         }         else{             alert("Enter a valid phone number");             return false;         }     }     </script>     </head><hr><body><h2>     Checking for a Valid Phone Number </h2> 3  <form name="formtest"  action="http://localhost/cgi-bin/environ.pl" method="post" 4  onSubmit="return ok_Phone(this);">  <p>         Please enter your phone: <BR> 5       <input type="text" size=40 name="user_phone">     <p>         <input type=submit value="Submit">         <input type=reset value="Clear">     </form></body></html> 

EXPLANATION

  1. The regular expression reads: Start at the beginning of the string, look for an optional literal opening parenthesis, followed by exactly three digits, and an optional closing parenthesis (the area code), followed by an optional dash, zero or more spaces, exactly three digits, zero or more spaces, an optional dash, and ending in exactly four digits, such as (222)-111-2345 or 222-111-2345 or 2221112345.

  2. The regular expression is matched, phform.user_phone.value , the test() method will return true , and the form will be submitted; otherwise , the user will be alerted to enter a valid phone number.

  3. The HTML form starts here and is named formtest .

  4. The onSubmit event handler is assigned as an attribute of the <form> tag. It will be activated when user presses the submit button. The handler, ok_Phone , passes the form as an argument. The this keyword refers to the form named formtest and returns a true or false value. If true , the form will be submitted.

  5. The user will enter his phone number in a text field. See Figure 13.44

    Figure 13.44. The user enters a valid phone number (top). Parentheses and the dash are optional; the user enters a number with too many digits, and an alert box appears (bottom).

    graphics/13fig44.jpg

Go to http://www.wtng. info , the World Wide Telephone Guide, to get a listing of phone formats for the world, country by country.

Figure 13.45. Go to http://www.wtng.info/ to look up phone formats around the world.

graphics/13fig45.jpg

For international phone numbers, the following formats are accepted:

+1 (123) 456 7888

+1123456 7888

+44 (123) 456 7888

+44(123) 456 7888 ext 123

+44 20 7893 2567

02345 444 5555 66

13.4.7 Checking for Valid E-Mail Addresses

When validating an e-mail address, you are looking for the typical format found in such addresses. There may be some domain names that are more than three characters, but it isn't typical. Also, just because the user types what looks like a valid e-mail address, that does not mean that it is; for example, the e-mail address santa@northpole.org uses a valid syntax, but that fact does not prove that santa is a real user.

E-mail addresses usually have the following format:

  • An @ sign between the username and address (lequig@aol.com)

  • At least one dot between the address and domain name ( .com, .mil, .edu, .se )

  • At least six characters ( a@b.se ) [3]

    [3] As of this writing, domain names have at least two characters.

Examples of valid e-mail addresses:

username@ mailserver .com

username@mailserver.info

username@mailserver.org.se

username.moretext@mailserver.mil

username@mailserver.co.uk

user-name.moretext.sometext@mailserver.se

To break down the regular expression

 
 /^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/; 

use the following steps:

Step 1:

^

Go to the beginning of the line.

Step 2:

([\-\w]+)\.?

The user name consists of one or more dashes or word characters grouped by parentheses, followed by one (or not one) literal period. Because the dot is outside the parentheses there will be either one or zero dots for the list of word characters, not two or three dots in a row.

Step 3:

(([\-\w]+)\.?)+

The user name may consist of more than one set of word characters separated by a single dots, as in Joe.Shmoe.somebody.

Step 4:

@

A literal @ symbol is required in the e-mail address.

Step 5:

([\-\w]+)\.?)+

The mail server's name is like the user's name, a group of word characters separated by a dot. Same as step 3.

Step 6:

[a-zA-Z]{2,4}

The domain name follows the mail server's name. A single dot separates the server from the domain. The domain name consists of between two and four alphabetic characters; e.g., savageman@imefdm.usmc.mil or patricia.person@sweden.sun.com .

Step 7:

$

The end of the line anchor assures that no extra characters can be added onto the end of the e-mail address.

Example 13.45 uses a regular expression to check for a valid e-mail address.

Example 13.45
 <html><head><title>Validating E-Mail Addresses</title>     <script language="JavaScript"> 1  function ok_Email(eform)  { 2  var regex = /^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/;  3       if(regex.test(eform.user_email.value)){ 4  return true;  }         else{ 5          alert("Enter a valid email address");            return false;         }     }     </script>     </head>     <hr>     <body>     <h2> Checking for Valid Email Address </h2> 6   <form name="formtest" 7       action="http://localhost/cgi-bin/environ.pl"         method="post" 8  onSubmit="return ok_Email(this);">  <p>     Please enter your email address: <BR>     <input type="text" size=40 name="user_email">     <p>     <input type=submit value="Send">     </body></html> 

EXPLANATION

  1. A function called ok_Email is defined. It takes one parameter, a reference to the form started on line 6.

  2. The regular expression is assigned the variable regex . The regular expression reads: Start at the beginning of the string (^), look for one or more alphanumeric characters and/or a dash followed by a literal dot (or not one). The literal period is outside the parentheses, meaning that in each group of word characters, there will be only one (or not one) period; e.g., abc.xyz. The entire expression is in parentheses followed by a + sign. This means that the pattern can be repeated one or more times; e.g., abc.xyz.yaddy.yady.yady. Next comes a literal @ symbol, required in all e-mail addresses. The mail server name comes right after the @ sign. Like the user name, it is represented by one or more alphanumeric characters or a dash, followed by a literal dot (\.). Now we have Joe.Blow@aol or DanSav@stamford , etc. This pattern, like the first pattern, can be repeated one or more times. The domain name part of the address comes next; a literal dot, and at least two but not more than four alphabetic characters, [a-zA-Z]{2,4} ; e.g., JoeBlow@Chico.com, danny@Stamford.edu, .se, .uk , etc. There are other varieties that could also be considered , such as john@localhost , but for most e-mail addresses, the regular expression used in this example should suffice.

  3. The regular expression test() method takes the value of the user input, user_email.value , and returns true if the pattern in the regular expression matched the user's input.

  4. The e-mail address entered is tested to be valid. A true value is returned and the form will be submitted to the server. A valid e-mail address does not mean that if mail is sent to that address it will necessarily be delivered; e.g., santa@northpole.org is syntactically valid, but there is no guarantee that santa is a real user (unless you still believe!).

  5. If an invalid e-mail address was entered, the alert box will appear with this message. The ok_Email() function will return false , and the form will not be submitted.

  6. The form named formtest starts here.

  7. This is the URL of the CGI script that will be called on the server side when the form is submitted.

  8. The onSubmit event handler is triggered when the user presses the submit button. The value assigned to the event is a function called ok_Email that will return true if the e-mail address is valid and false , if not. The form will be sent to the server only if the return value is true . See Figure 13.46.

    Figure 13.46. The user enters a valid e-mail address.

    graphics/13fig46.jpg

13.4.8 Credit Card Validation

When validating a credit card number, you can do some preliminary checking but real card validation is done on the server side through a software product designed specifically for that purpose. [4] Before issuing a card, there are certain rules that must be followed when creating card numbers, such as how many numbers there are, what prefix is used by a particular card type, whether the entire number fits a certain formula, and valid expiration dates. For preliminary checking, you can test, for example, to see if a person enters valid digits for a Visa card and that the expiration date is later than the current date, but you can't really tell if the user's card has gone over the limit, was cancelled or stolen, or that he even owns it. Checking whether the card is active and has a sufficent balance to cover a sale is performed by the banking system backing the card.

[4] For a guide to credit card validation software, go to http://www.winsite.com/business/cc/.

The Expiration Date of the Card

A valid expiration date is a month and year that haven't gone by. The month and year are represented as two digits: 01 for January, 11 for November, and 03 for the year 2003. The following example defines a function to test for a valid expiration date based on a one to two-digit month and a two-digit or four-digit year.

Example 13.46
 <html>     <head>     <title>Testing Expiration Dates</title>     <script language="javascript"> 1  function validExpire(form) {  2       var now = new Date(); 3       var thismonth = (now.getMonth() + 1); 4       var thisyear = now.getFullYear() ; 5       var expireYear = parseInt(form.expireYear.value);         var yearLength = form.expireYear.value.length;         var expireMonth = parseInt(form.expireMonth.value);         if(yearLength == 2){             expireYear += 2000;         } 6  if ((expireMonth < thismonth  && expireYear == thisyear)   expireMonth > 12){  alert("Invalid month");  return false;  } 7  else if (expireYear < thisyear)  {            alert("Invalid year");  return false;  }         else {  return true;  }     }     </script>     </head>     <body> 8  <form name="myForm"   action="http://127.0.0.1/cgi-bin/env.cgi"  9  onSubmit="return validExpire(this)">  <p>     Enter the month (02 or 2):     <input name="expireMonth" type="text" size=5>     <p>     Enter the year (2003 or 03):     <input name="expireYear" type="text" size=5>  <input type="submit" value="submit">  <input type="reset" value="clear">     </form>     </body>     </html> 

EXPLANATION

  1. A function called validExpire() is defined. It takes one parameter, a reference to a form. Its purpose is to validate the expiration date of a credit card.

  2. A new Date object is created and assigned to the variable called now .

  3. Using the getMonth() method, we get this month (months start at zero) and add 1.

  4. Using the getFullYear() method, we get the current year, as 2003 .

  5. The parseInt() function converts the expiration year, as typed in by the user, to an integer. Then we get the length of the year, and convert the month into an integer. If the number of characters in the year, yearLength , is 2, then 2000 is added to the expireYear value. If the user typed 02, then the new value is 2002.

  6. If the value of expireMonth is less than the value of thisMonth and the value of expireYear is equal to the value of thisyear, or the value of expireMonth is greater than 12, the number entered is invalid. So a card in invalid if it has a month prior to this month and the card expires this year, or the month is over 12, because there are only 12 months in a year.

  7. If the expiration year is prior to this year, it is also invalid.

  8. The form starts here.

  9. The onSubmit event handler is triggered after the user fills out the form and presses the submit button. When he does, the function called validExpire() is called. It will return true if the expiration date is valid, and the form will be sent to the URL assigned to the action attribute of the form. See Figure 13.47.

    Figure 13.47. The form before the user enters anything (left); the user enters a month and year, but the month has already gone by (right).

    graphics/13fig47.jpg

Checking for Valid Type, Prefix, and Length

In Figure 13.49 the major credit cards are listed along with the identifying characteristics of account numbers for each. All the characters must be numbers. Each type of card has a prefix value; e.g., MasterCard's prefix is a number between 51 and 56, and Visa's is the number 4. Validation routines to check for a prefix and the correct number of characters are shown in Example 13.47.

Figure 13.49. Some valid credit cards, their prefix, length, and whether they pass the Lunh test based on modulus 10, shown below. Source: http://www.beachnet.com/~hstiles/cardtype.html.

graphics/13fig49.jpg

Steps for credit card validation:

  1. Remove any spaces or dashes, then test that the result is a numeric value.

  2. Check to see if the user has selected a valid credit card type such as MasterCard or Visa, the correct prefix for the card, and a valid length for the number of characters in the card.

  3. Apply the Lunh formula for further validation.

Example 13.47
 <html>     <head>     <title>Checking for Valid CC Type and Length</title>     <script language="JavaScript"> 1  function checkCC(myForm){  var cc_type;        var cc_length; 2  if (myForm.select1.selectedIndex==0){  cc_type="Visa";        }        else if(myForm.select1.selectedIndex==1){            cc_type="MasterCard";        }        else if(myForm.select1.selectedIndex==2){            cc_type="Discover";        }        else {            alert("You didn't select a card type.");        } 3  cc_length=myForm.text.value.length;  4  switch(cc_type){  5      case "Visa" : 6          if (cc_length == 13  cc_length == 16){  return true;  }            else{               alert("Invalid length");  return false;  }            break; 7      case "MasterCard":            if (cc_length == 16){  return true;  }            else{               alert("Invalid length");  return false;  }            break; 8      case "Discover":            if (cc_length == 16){  return true;  }            else{               alert("Invalid length");  return false;  }            break;        default:            alert("Invalid type");  return false;  break;        }     }     </script>     </head>     <body bgcolor="lightblue">     <font size="+1" face="arial"> 9  <form name="form1" onSubmit="return checkCC(this);">  Please select a credit card from the menu:     <p> 10  <select name="select1" size="3">  <option value="Visa">Visa</option>        <option value="MC">MasterCard</option>        <option value="Dis">Discover</option>     </select>     <p>     Please enter your card number:     <p> 11  <input type=textbox name="text" size=30>  <p> 12  <input type=submit value="Check card">     <input type=reset>     </form>     </body>     </html> 

EXPLANATION

  1. A function called checkCC() is defined. It takes one parameter, a reference to a form.

  2. If the value of selectedIndex is 0 , the first option in the select list was chosen , a Visa card. The rest of the statements in this if block check to see which card was selected if it wasn't this one.

  3. The variable cc_length is assigned the number of characters that were typed into the text box; that is, the number of characters in the credit card number.

  4. The switch statement will be used to check for valid card number lengths for whichever card the user selected from the select menu. The variable cc_type contains the card type: Visa, MasterCard, or Discover.

  5. If the card is a Visa card, the case statements will be used to check for a valid length.

  6. The valid length for the Visa credit card number is between 13 and 16 characters (as shown in Figure 13.49). If the card number length is between these numbers, true is returned.

  7. MasterCard is checked here. Its number must consist of 16 characters.

  8. Discover is checked here. Its number must consist of 16 characters.

  9. The form starts here. The onSubmit handler will be triggered when the user presses the submit button. At that time the credit card will be checked for a valid number of characters in the number provided by the user. This is not a complete check. You can combine the other functions from this section to provide a more thorough check; we haven't checked here to see if the value entered is numeric, has strange characters, or empty fields.

  10. The select menu starts here with three options, each a credit card type.

  11. This is the text box where the user enters the card number.

  12. When the user presses the submit button, the onSubmit handler is invoked, and if the credit card number passes the validity test, off goes the form!

Figure 13.48. The number of characters in the credit card number should be 16 for Discover card.

graphics/13fig48.jpg

The Lunh Formula

The credit card number can be subjected to an additional mathematical test, called the Lunh formula, which it must pass in order to be valid. The following steps are required to validate the primary account number:

Step 1. Double the value of every other digit starting with the next-to-right-most digit.

Step 2. If any of the resulting values has more than two digits, then its digits must be added together to produce a single digit.

Step 3. Add the sum of all the digits not doubled in Step 1 to the sum of the digits transformed from Steps 1 and 2.

Step 4. If the result is exactly divisible by 10 (that is, if the result ends in a zero, 30, 40, 50, etc.), then the number is validproviding of course that it's of the correct length and bears a correct prefix for that type of card.

For example, to validate the primary account number 49927398716:

Step 1. Starting from the next to the right-most digit, multiply every other number by 2 (the number in bold text).

 
 4  9  9  2  7  3  9  8  7  1  6   9x2   2x2   3x2   8x2   1x2    18    4     6     16    2 
Step 2. If any numbers resulting from Step 1 have more than one digit, add those numbers together.

 
 (1+8)  (1+6)   9      7 
Step 3. Add up the top row of numbers that were not doubled (not in bold) to the bottom row of numbers after Step 2 was finished. Bottom numbers are in parentheses.

 
 4 + (9) + 9 + (4) + 7 + (6) + 9 +(7) + 7 + (2) + 6 
Step 4. If the result of Step 3 is divisible exactly by 10 (i.e., leaves no remainder), the card is valid. The result of Step 3 is 70. The card number is valid if the card type is valid, as long as the length of numbers entered is valid, and it has the correct prefix for that type of card.

13.4.9 Putting It All Together

After writing the functions that validate each field of the form, they will be put together in a single script to check all form entries. The following example combines just two of the functions, to keep the example from being too large. One function, ok_Form() , calls the functions that check individual entries; for example, ok_Email() checks for valid e-mail and returns either true or false, and ok_Phone() checks for a valid phone number. After all of the entries have been checked, the ok_Form() function returns either true or false to the onSubmit event handler. If ok_Form() returns true , the form will be submitted to the server; if not, it is stopped . If we add in all the credit card validation functions, this program will get really large. Why don't you try it?

Example 13.48
 <html><head><title>Validating a Form</title>     <script language="JavaScript"> 1  function ok_Email(emform){  2       var regex=/^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/; 3       if(regex.test(eform.user_email.value)){  return true;  }         else{             alert("Enter a valid email address");  return false;  } 4  function ok_Phone(phform){  5      var regex = /^\(?\d{3}\)?-?\s*\d{3}\s*-?\d{4}$/; 6  if(regex.test(phform.value)){   return true;  }        else{  return false;  }     } 7  function ok_Form(myform){  8  if (ok_Email(myform.user_email)== false){  9  alert("Invalid email address");  10  myform.user_email.focus();  11  myform.user_email.select();  12        return false;        } 13  if (ok_Phone(myform.user_phone) == false)  {           alert("Invalid phone number");           myform.user_phone.focus();           myform.user_phone.select();  return false;  } 14  return true;  }     </script>     </head>     <hr>     <body bgcolor="lightgreen"> <font face="arial" size="+1">     <h2> Checking Form Input</h2>     <form name="myform"        action="http://localhost/cgi-bin/environ.pl" method="post" 15  onSubmit="return ok_Form(this);">  <p>     Please enter your email address: <BR>     <input type="text" size=40 name="user_email">     <p>     Please enter your phone number: <BR>     <input type="text" size=12 name="user_phone">     <p>     <input type=submit value="Send">     </form>     </body>     </html> 

EXPLANATION

  1. The function to validate an e-mail address is defined. It is called by the ok_Form() function on line 8.

  2. The local variable called regex is assigned a regular expression, explained in Example 13.45.

  3. The e-mail address entered by the user, eform.user_email.value , is tested against the regular expression for validity. The regular expression test() method returns true or false to the ok_Form function, line 8.

  4. The function to validate a phone number is defined. It is called by the ok_Form() function on line 13.

  5. The local variable called regex is assigned regular expression.

  6. The phone number entered by the user, eform.user_phform.value , is tested against the regular expression for validity. The regular expression test() method returns true or false to the ok_Form function, line 13.

  7. This is the big function that returns the final verdict. Did the user provide a valid e-mail address and phone number? If so, the function returns true , line 14.

  8. The ok_Email() function is called with the user's e-mail input. If the ok_Email() function returns false , the user entered an invalid address, and he will be alerted.

  9. The alert dialog box sends this message if the e-mail address is not valid.

  10. The focus() method puts the cursor in the text box, so that the user can start typing there.

  11. The select() method highlights the text in a field.

  12. If false is returned to the onSubmit handler on line 15, the form will not be submitted.

  13. If an invalid phone number was entered, false will be returned to the onSubmit handler on line 15.

  14. If both the e-mail address and the phone number are valid, the ok_Form() function returns true to the event handler on line 15, and the form will be submitted to the server's URL assigned to the form's action attribute.

  15. The onSubmit event is triggered when the user presses the submit button. The handler is a function called ok_Form() . It is the main validation function for this form. If true is returned, the form will be submitted; otherwise, not. See Figures 13.50 and 13.51.

    Figure 13.50. The user enters a valid e-mail address (top); the user entered an invalid e-mail address because there is only one letter in the domain name (bottom).

    graphics/13fig50.jpg

    Figure 13.51. The focus() and select() methods focus on and highlight the invalid entry.

    graphics/13fig51.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net