Học JavaScript qua ví dụ part 90 doc

13 183 0
Học JavaScript qua ví dụ part 90 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

ptg 17.5 Form Validation with Regular Expressions 783 17.5.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 specifi- cally for that purpose. 4 Before issuing a card, there are certain rules that must be fol- lowed when creating card numbers, such as how many numbers there are, what prefix EXPLANATION 1 A function called ok_Email is defined. It takes one parameter, a reference to the form started on line 6. 2 This got the highest score at http://www.regexlib.com. When you are looking for a regular expression that covers all possibilities, you might spend a week and still not have caught everything. This is where the libraries come in handy. Somebody has already done the hard work. 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; for example, san- ta@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 mes- sage. The ok_Email() function will return false, and the form will not be submit- ted. 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 clicks 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 17.49. Figure 17.49 The user enters a valid e-mail address. From the Library of WoweBook.Com ptg 784 Chapter 17 • Regular Expressions and Pattern Matching 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 can- celled or stolen, or that he or she even owns it. Checking whether the card is active and has a sufficient balance to cover a sale is performed by the banking system backing the card. 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. 4. For a guide to credit card validation software, go to http://www.winsite.com/business/cc/. EXAMPLE 17.46 <html> <head><title>Testing Expiration Dates</title> <script type="text/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> From the Library of WoweBook.Com ptg 17.5 Form Validation with Regular Expressions 785 <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><p> Enter the year (2003 or 03): <input name="expireYear" type="text" size=5 /> <input type="submit" value="submit" /> <input type="reset" value="clear" /> </p> </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 ex- pireYear is equal to the value of thisyear, or the value of expireMonth is greater than 12, the number entered is invalid. So a card is 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 clicks the submit button. When he or she 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 17.50. EXAMPLE 17.46 (CONTINUED) From the Library of WoweBook.Com ptg 786 Chapter 17 • Regular Expressions and Pattern Matching Figure 17.50 The form before the user enters anything (left); the user enters a month and year, but the month has already gone by (right). Checking for Valid Type, Prefix, and Length. In Figure 17.51 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; for example, MasterCard’s prefix is a number between 51 and 56, and Visa’s is the number 4. Vali- dation routines to check for a prefix and the correct number of characters are shown in Example 17.47. These are 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 17.47 <html> <head><title>Checking for Valid CC Type and Length</title> <script type="text/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"; } From the Library of WoweBook.Com ptg 17.5 Form Validation with Regular Expressions 787 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"> <big> Continues EXAMPLE 17.47 (CONTINUED) From the Library of WoweBook.Com ptg 788 Chapter 17 • Regular Expressions and Pattern Matching 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><p> 11 <input type=textbox name="text" size=30 /> </p> 12 <input type=submit value="Check card"> <input type=reset> </form> </big> </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 select- ed 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 con- tains 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 17.51). 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 clicks 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. EXAMPLE 17.47 (CONTINUED) From the Library of WoweBook.Com ptg 17.5 Form Validation with Regular Expressions 789 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 clicks the submit button, the onSubmit handler is invoked, and if the credit card number passes the validity test, off goes the form! See Figure 17.52. Figure 17.51 Some valid credit cards, their prefix, length, and whether they pass the Lunh test based on modulus 10, shown later. Source: http://www.beachnet.com/~hstiles/cardtype.html. Figure 17.52 The number of characters in the credit card number should be 16 for Discover Card. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 790 Chapter 17 • Regular Expressions and Pattern Matching The Lunh Formula. The credit card number can be subjected to an additional math- ematical test, called the Lunh formula, which it must pass 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-rightmost 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 (i.e., if the result ends in a zero, 30, 40, 50, etc.), then the number is valid—providing of course that it’s of the cor- rect 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. From the Library of WoweBook.Com ptg 17.5 Form Validation with Regular Expressions 791 17.5.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. Example 17.48 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 17.48 <html> <head><title>Validating a Form</title> <script type="text/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; } Continues From the Library of WoweBook.Com ptg 792 Chapter 17 • Regular Expressions and Pattern Matching 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> <body bgcolor="lightgreen"> <font face="arial" size="+1"> <hr /> <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><p> Please enter your phone number: <br /> <input type="text" size=12 name="user_phone" /> </p> <input type=submit value="Send" /> </form> </font> </body> </html> EXPLANATION 1 The function to validate an e-mail address is defined. It is called by the ok_Form() function on line 7. 2 The local variable called regex is assigned a regular expression, explained in Ex- ample 17.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 7. 4 The function to validate a phone number is defined. It is called by the ok_Phone() 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_Phone function, line 13. EXAMPLE 17.48 (CONTINUED) From the Library of WoweBook.Com [...]... all jumping on the bandwagon to support them They are particularly useful in JavaScript for validating input data and with regular expression metacharacters give you endless ways to match patterns After learning how to use regular expressions and pattern matching you should be able to: 1 2 3 4 5 6 7 8 9 10 Define a literal regular expression with JavaScript Define a regular expression object and use . Library of WoweBook.Com ptg 784 Chapter 17 • Regular Expressions and Pattern Matching is used by a particular card type, whether the entire number fits a certain formula, and valid expiration dates 17.46 <html> <head><title>Testing Expiration Dates</title> <script type="text /javascript& quot;> 1 function validExpire(form) { 2 var now = new Date(); 3 var thismonth = (now.getMonth(). the value of expireMonth is less than the value of thisMonth and the value of ex- pireYear is equal to the value of thisyear, or the value of expireMonth is greater than 12, the number entered

Ngày đăng: 04/07/2014, 02:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan