Học JavaScript qua ví dụ part 43 ppt

12 193 0
Học JavaScript qua ví dụ part 43 ppt

Đ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 11.5 Programming Input Devices (Controls) 401 11.5.1 Simple Form Validation Have you ever filled out a form to buy something, clicked the submit button, waited, waited, and then received a big red message saying that the card number you entered was invalid? And then after all that waiting, you had to retype the entire form because all of the fields were reset? By letting JavaScript do some preliminary checking of the form input for obvious mistakes and erroneous information, you can save the user a lot of time and aggravation. Then, after the preliminary checking is done, the form is ready to go off to a server program, such as Perl or PHP, where it can be further vali- dated and processed. This section will show you a little about validating forms: doing preliminary checking to see if a password is the correct length, making sure a field isn’t empty, checking for unwanted characters, and more. Chapter 17, “Regular Expres- sions and Pattern Matching,” shows you how to validate the format for e-mail addresses, credit cards, zip codes, names, phone numbers, Social Security numbers, and the like by using regular expressions, a powerful pattern matching tool provided by JavaScript. Checking for Empty Fields. Forms often have mandatory fields that must be filled out before the form can be submitted. The following example checks for empty fields. EXAMPLE 11.26 <html> <head><title>An HTML Form and the onSubmit Event Handler</title> <script type="text/javascript"> 1 function checkForm(yourinfo){ 2 if(yourinfo.namestring.value == "" || yourinfo.namestring.value == null){ // Check for an empty string or null value 3 alert("Please type in your name"); 4 return(false); } else{ 5 return(true); } } </script> </head> <body> <b> 6 <form name="info" action="http://cgi-bin/bookstuff/form1.cgi" method="post" 7 onSubmit="return checkForm(this);"> <big><p> Continues From the Library of WoweBook.Com ptg 402 Chapter 11 • Working with Forms and Input Devices Type your name here: 8 <input type="text" name="namestring" size="50"> </p> 9 <input type="submit" value="Submit" /> <input type="reset" value="Clear" /> </big> </form> </body> </html> EXPLANATION 1 The function called checkForm() has one parameter, yourinfo, which is a reference to the form defined on line 6. 2 If the user didn’t enter anything into the textbox, the value of the input type will be null. The expression if(yourinfo.namestring.value == “”) checks for an empty field. 3 The user didn’t enter anything into the textbox, an alert dialog box will appear on the screen, and after he presses OK, he will have a chance to fill out the form again. 4 If false is returned from this function, the form will not be submitted to the server. 5 If true is returned from this function, the form will be submitted to the server. 6 The HTML form starts here. The form, document.forms[0], is named info. The ac- tion attribute contains the URL of the program that will process the form, a CGI script on the server. The method attribute defines the HTTP method that deter- mines how the data will be sent to the server. 7 The onSubmit event is an attribute of the HTML <form> tag. It is triggered when the user clicks the Submit button. The event handler is a function called check- Form(). Its argument is this, same as document.forms[0] ). The return keyword is required when using the onSubmit event handler. One of two values will be re- turned: either true or false. 8 The input type for this form is a text field box. Its name is namestring and it can hold a string of up to 50 characters. 9 The input type is the Submit button. When the user clicks this button, the onSub- mit event handler on line 7 is activated. See Figure 11.46. EXAMPLE 11.26 From the Library of WoweBook.Com ptg 11.5 Programming Input Devices (Controls) 403 Checking for Alphabetic Characters. If checking input fields for alphabetic characters, such as a user name, the following example will go through a loop evaluating each character in a string to guarantee it is an alphabetic. See Chapter 17 for more on this type of validation. Figure 11.46 Using the onSubmit event handler to stop a form if the user didn’t enter anything in the field. EXAMPLE 11.27 <html> <head><title>Verifying a Name</title> <script type="text/javascript"> 1 function validate(form){ 2 if(alpha(form.first) == false){ alert ("First name is invalid"); return false; } 3 if(alpha(form.last) == false){ alert("Last name is invalid"); return false; } return true; } 4 function alpha(textField ){ 5 if( textField.value.length != 0){ 6 for (var i = 0; i < textField.value.length;i++){ 7 var ch= textField.value.charAt(i); /* alert(ch); Using alert to see what characters are coming in */ 8 if((ch < "A" || ch > "Z") && (ch< "a" || ch >"z")){ return false; } } } Continues From the Library of WoweBook.Com ptg 404 Chapter 11 • Working with Forms and Input Devices else { 9 return true; } } </script> </head> <body bgcolor="lightgreen"> <font face=verdana> <strong> 10 <form name="alphachk" onSubmit="return validate(this);"> Enter your first name: <br /> 11 <input name="first" type="text" size=60> <p> Enter your last name: <br /> 12 <input name="last" type="text" size=60> <p> 13 <input type=submit value="Check it out"> <input type=reset> </form> </strong></font> </body> </html> EXPLANATION 1 A JavaScript function called validate() is defined. It takes one parameter, a refer- ence to a form object. 2 The if expression invokes a function, called alpha(), and passes the text object to it. The first name is validated by the alpha() function. If false is returned, the block is entered and the user is alerted that he or she did not enter a valid first name. If this function returns false to the onSubmit handler that invoked it, on line 10, the form will not be submitted. 3 As in line 2, the alpha() function is being called, only this time to verify the last name of the user. 4 The function called alpha() is defined. All the validation work is done here. This function will validate that the user entered something in the textbox, and that what he or she entered is alphabetic characters, and only alphabetic characters, either uppercase or lowercase. 5 If the length of characters entered in the text field is not equal to 0, then the block is entered. EXAMPLE 11.27 (CONTINUED) From the Library of WoweBook.Com ptg 11.5 Programming Input Devices (Controls) 405 Checking E-Mail Addresses. You are frequently asked to include your e-mail address when filling out a form. There are some requirements for a valid e-mail address such as TommyTucker@somewhere.com. One requirement is that there is an @ symbol after the user name, and that there is at least one dot (.) in the address. The following example is a preliminary check for the existence of both of those characters, but it is far from a complete check. See Chapter 17 for a much more robust version of e-mail vali- dation using regular expressions. 6 The for loop is used to check each character, one at a time, that was entered in the text field. 7 The charAt() string method returns a character at a specified position in the string. Each time through the loop, a new character is assigned to the variable, ch. 8 This is the test for alphabetic characters. Because each character is represented in- ternally as an ASCII number, ( “A” is ASCII 65, “B” ASCII 66, etc.), any character outside the range “A” to “Z” and “a” to “z” is not an alphabetic character. 9 If true is returned by the alpha() function, the form will be submitted. 10 The name of the form is alphachk. The onSubmit event is triggered when the user clicks the Submit button on line 13. 11 The input type is a text field, called first. This is where the user will enter his or her first name. 12 The input type is a text field, called last. This is where the user will enter his or her last name. 13 The input type is a Submit button. When the user clicks this button, the onSubmit event is triggered, and if the form was valid, it will be submitted to the server. (In this example, it isn’t going anywhere, because the action attribute of the form wasn’t specified.) See Figure 11.47. Figure 11.47 The user enters a valid first name and an invalid last name. EXPLANATION From the Library of WoweBook.Com ptg 406 Chapter 11 • Working with Forms and Input Devices EXAMPLE 11.28 <html> <head><title>Checking Email</title> <script type="text/javascript"> 1 function email(form){ // Validate the address 2 if(form.address.value.indexOf("@") != -1 && form.address.value.indexOf(".") != -1){ alert("OK address!"); 3 return true; } else { alert("Invalid address"); 4 return false; } } </script> </head> <body bgcolor="lightgreen"> <font face=verdana> <b> <div align="center"> 5 <form name="mailchk" action="http://cgi-bin/ml.pl" method="post" onSubmit="return email(this);"> Enter your email address: <p> 6 <input name="address" type="text" size=60 /> </p><p> 7 <input type=submit value="Check it out" /> <input type=reset /> </p> </form> </div></b></font> </body> </html> EXPLANATION 1 A JavaScript function called email() is defined. It takes one parameter, a reference to a form. 2 If the string method, indexOf, does not return a –1, then the @ character and a dot (.) were found in the value entered by the user in the textbox, and an alert mes- sage will let the user know his or her e-mail address is okay. This is where the val- idation takes place. 3 If true is returned, the form will be submitted. From the Library of WoweBook.Com ptg 11.5 Programming Input Devices (Controls) 407 Checking Password Fields. There are a number of checks made on password entries. Does it have the right number of characters? Does it contain one numeric char- acter? Can it contain upper and lowercase characters? The following example is a simple validation routine to check for alphanumeric characters and that the number of charac- ters in the password field is not less than six. 4 If false is returned, the form is stopped, and will not be submitted. 5 The HTML form, called mailchk, starts here. The onSubmit event will be triggered when the user clicks the submit button on line 7. 6 The form’s input type is a textbox named address that will hold up to 60 characters. 7 When the user clicks the submit button, the onSubmit handler on line 5 is trig- gered. It invokes the handler function, called email, and passes a reference to the form as an argument. See Figures 11.48 and 11.49. Figure 11.48 The user enters a valid e-mail address. Figure 11.49 The user enters an invalid e-mail address. A dot is missing in the address. EXPLANATION From the Library of WoweBook.Com ptg 408 Chapter 11 • Working with Forms and Input Devices EXAMPLE 11.29 <html> <head><title>Verifying a Password</title> <script type="text/javascript"> 1 function valid(form){ 2 if( form.pass.value.length == 0 ){ alert("Please enter a password"); return false; } 3 if( form.pass.value.length < 6 ){ alert("Password must be at least 6 characters"); return false; } for (var i = 0; i < form.pass.value.length;i++){ var ch= form.pass.value.charAt(i); 4 if((ch < "A" || ch > "Z") && (ch< "a" || ch >"z") && (ch < "0" || ch > "9")){ alert("Password contains illegal characters"); return false; } } 5 alert("OK Password"); return true; } </script> </head> <body bgcolor="red"> <font face="verdana"> <b><div align="center"> 6 <form name="passchk" onSubmit="return valid(this);"> Enter your password: <br /> 7 <input name="pass" id="pass" type="password" size=33 /> <p> <input type=submit value="Submit Password" /> <input type=reset /> </p> </form> </div> </font> </body> </html> From the Library of WoweBook.Com ptg 11.6 What You Should Know 409 11.6 What You Should Know Any Web site that is trying to sell you something will have a form. They are at the heart of Web commerce. This chapter focused on how to create forms and different input devices used to collect the data, textboxes, checkboxes, drop-down menus, and so on. You learned how JavaScript can access this data and manipulate it; for example, how to change the text in a box, verify that there was any input, stop a submission, open up EXPLANATION 1 A JavaScript function called valid() is defined. It takes one parameter, a reference to a form. 2 If the password entered by the user has a length of 0 characters, an alert message is sent. 3 If the password entered by the user has a length of less than 6 characters, an alert message is sent. 4 If the value of the password entered by the user contains any character that is not an alphabetic character and not a number, an alert message is sent. 5 If the password was at least 6 characters and contained only alphanumeric char- acters (letters and numbers), then the validation test was passed, and the user is alerted. A value of true is returned to the onSubmit handler, allowing the form to be submitted. 6 The HTML form called passchk is started here. Its onSubmit handler is triggered when the user clicks the submit button. 7 The input type is a password box, called pass. This is where the user will enter his or her password. See Figure 11.50. Figure 11.50 The user enters a password of less than 6 characters (left) or enters a password that contains illegal characters (right). From the Library of WoweBook.Com ptg 410 Chapter 11 • Working with Forms and Input Devices another window and display the form data, do some simple validation, and so on. After going through this chapter, you should know: 1. What the DOM tree looks like to JavaScript. 2. Why we use the Legacy DOM with forms. 3. How to create HTML forms and input devices. 4. What two methods are used to send data to a server. 5. How the browser bundles up the input data. 6. What name/value pairs represent in forms. 7. What a server-side program does. 8. How the form object and the elements object are used. 9. When to use the name and the id attributes. How do they differ? 10. How to catch a form before it is submitted to a server. 11. How to reference the input devices in a JavaScript function. 12. How to stop form data from being submitted. 13. How to program input devices/controls. 14. How the this keyword is used with forms. 15. How the button input device differs from the submit button. 16. How to use an event handler with a form. 17. How the form’s submit() method differs from the onSubmit event handler. 18. How to change the text in a textbox with JavaScript. 19. What the blur() and focus() methods do. 20. How to use multiple selects. 21. How the selectedIndex property works with drop-down menus. 22. How to test for input that does not contain alphabetic data. 23. How JavaScript can tell which button was selected in a list of radio buttons. ExerciseseeExExercisesdddEeeeee From the Library of WoweBook.Com [...]... devices Use JavaScript to print out the names and values in the forms 4 Add a button to the last example If the user clicks it, display the form content in another window 5 Create two text fields In one text field, the user will enter his or her birth month and day Write a JavaScript program that will print the number of days until his or her birthday in the second text field 6 Write a JavaScript function... or her name in only uppercase letters Send the form to a server program if it is valid 10 Create a form with radio buttons representing different colors Use the id attribute for each radio button In a JavaScript program, the getElementsById() will return a reference to the radio button that was selected Change the background color to the color that was selected From the Library of WoweBook.Com This . learned how JavaScript can access this data and manipulate it; for example, how to change the text in a box, verify that there was any input, stop a submission, open up EXPLANATION 1 A JavaScript. or her birth month and day. Write a JavaScript program that will print the number of days until his or her birthday in the second text field. 6. Write a JavaScript function that will finish. <head><title>An HTML Form and the onSubmit Event Handler</title> <script type="text /javascript& quot;> 1 function checkForm(yourinfo){ 2 if(yourinfo.namestring.value == ""

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

Từ khóa liên quan

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

Tài liệu liên quan