JavaScript is not a true security measure in itself, but rather an added level of security and a convenience to your users. Because JavaScript is a client-side technology (whereas PHP is server-side), incorporating it into your pages can save users the hassle of having to send the form data back to the server before seeing there are problems. Instead, you can use JavaScript to immediately run through some tests and then, if the data passes, send the form information along to PHP. I say that JavaScript in itself is not a security measure because it can be easily turned off in a user's browser (Figure 10.14), rendering it completely useless. It is critical that you view JavaScript in this light and continue to use PHP as your primary security measure. Figure 10.14. Most of today's Web browsers allow for disabling all JavaScript. As a demonstration of this, I'll create a form for submitting URLs. Some basic, easy-to-follow JavaScript will be incorporated to validate the data in the Web browser. In the next section of this chapter, PHP scripts will further check the submitted data using regular expressions. To validate forms with JavaScript 1. | Create a new HTML document in your text editor (Script 10.6).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd> <html xmlns="http://www.w3.org/1999/ xhtml xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset= iso-8859-1 /> <title>Submit a URL</title> Script 10.6. The submit_url.html page uses JavaScript in the client (the Web browser) to prevalidate a form. For this example, I'll be making one HTML page that displays the form and a separate PHP script that handles it.
| 2. | Create a JavaScript section and begin a function.
<script type="text/javascript" language="Javascript> <!-- // Hide script contents from old browsers. function check_data(my_form) { var problem = false; JavaScript can go anywhere within an HTML document using the script tags, but preferably it'll be placed within the HTML head.
The check_data() function will be called when the form is submitted. Its only purpose will be to validate all the form inputs. This function receives one argument: the form being validated. The problem variable (variables in JavaScript do not use an initial dollar sign) will be used as a flag indicating if there are any problems.
| 3. | Validate that the user entered a name.
if (my_form.name.value == "") { alert ("Enter your name."); my_form.name.value = "*** Name"; my_form.name.focus(); problem = true; } A barebones validation checks that the field isn't empty. To do so, I refer to the field's value, using the formname.fieldname.value syntax. If the user did not enter a value, then an alert pop-up window will be created (Figure 10.15) by the alert() line. Next, the name field will be given the value of *** Name to highlight it, and the user's attention will be directed to the name field in the Web browser (Figure 10.16) via JavaScript's focus() method. Finally, if there was a problem, the problem variable is set to true.
Figure 10.15. JavaScript's alert() function will make a pop-up box like this one. Figure 10.16. JavaScript's focus() function will highlight an element like the text box here (the actual results will vary by browser).
| 4. | Repeat the process for the email address and the URL.
if (my_form.email.value == "") { alert ("Enter your email address."); my_form.email.value = "*** Email Address; my_form.email.focus(); problem = true; } if (my_form.url.value == "") { alert ("Enter the URL."); my_form.url.value = "*** URL"; my_form.url.focus(); problem = true; } The two validation routines are variants on the steps taken to check the name input, replacing instances of name with email and url accordingly.
| 5. | Validate that a URL category was selected.
if ((my_form.url_category. selectedIndex == 0) || (my_form. url_category.value == 0) ) { alert ("Please select a category for this URL."); problem = true; } Using JavaScript on pull-down menus is one of the many ways in which Web browsers differ. The my_form.url_category.value == 0 code will work for some browsers, but you have to use my_form.url_category.selectedIndex == 0 for others to function properly. I've included both as my conditional with an OR (the double pipe) linking them.
| 6. | Check if there was a problem and then complete the JavaScript.
if (problem) { return false; } else { return true; } } //--> </script> The logic here may seem a little backward, so I'll explain in detail. The value returned by this functiontrue or falsedetermines whether or not the form will be submitted to the handling page (true means go ahead and submit the data). If a problem was found, then false should be returned, indicating that the form data should not be submitted.
Turning to the problem variable, it was initially assigned the value of false (i.e., no problem exists). If the form passed all four tests, problem will still be equal to false and the function can return true, indicating that the data is valid. If the form failed one or more tests, problem will be equal to true, so the function should return false, leaving the user on this form page.
| 7. | Complete the HTML head, begin the body, and start the form.
</head> <body> <!-- Script 10.6 - submit_url.html --> <form name="url_form" action="handle_submit_url.php method="post onsubmit="return check_data(this)"> When validating forms with JavaScript, the most important line of code is this last one here, which begins the form. In it, I have named the form (url_form) and requested that when the submit button is pressed (onsubmit), the check_data() function be called. The function call passes the current objectin JavaScript this always refers to the current objectto the check_data() function.
| 8. | Complete the form.
<fieldset><legend>Enter your information in the form below: </legend> <p><b>Your Name:</b> <input type="text name="name" size="40" maxlength="60 /></p> <p><b>Email Address:</b> <input type="text name="email" size="40" maxlength="60 /> </p> <p><b>URL:</b> <input type="text" name="url size="40" maxlength="80 /></p> <p><b>URL Category:</b> <select name="url_category> <option>Choose One</option> <option value="3">Code Libraries </option> <option value="6">General Database </option> <option value="5">General MySQL </option> <option value="1">General PHP </option> <option value="4">Programming </option> <option value="2">Web Development </option> </select></p> </fieldset> <div align="center"><input type="submit name="submit" value="Submit /></div> </form> In the formal application of this script in Chapter 12, "ExampleContent Management," I'll generate the pull-down menu using the content database. For now I've hard-coded the url_category values (although they do correlate to those established in Chapter 5, "Advanced SQL and MySQL").
| 9. | Finish the HTML page.
</body> </html>
| 10. | Save the file as submit_url.html and test in your Web browser (Figures 10.17 and 10.18).
Figure 10.17. A pop-up alert will be created if any field is omitted. Figure 10.18. Each text field that is not filled out is highlighted using asterisks. You do not need to upload this to your Web server if you would prefer not to, since it's a simple HTML page. In any case, once the form passes validation, you'll see a Page Not Found error because the handling script has yet to be written.
| Tips Another way to refer to a form's element is to use the formal document.formname.inputname syntax. By passing the check_data() function the form (this), I was able to refer just to my_form.inputname, which I find to be easier. Many people find alert prompts to be annoying (because, well, they are). When using JavaScript to validate forms, you may want to reserve alert boxes for only the most critical fields. Alternatively, you can check for empty fields by seeing if their lengththe number of characters enteredis less than or equal to 0. The code would be if (my_form.inputname.value. length <= 0)
Using JavaScript for security is kind of like having a This house is protected by… sticker on your site's window: it implies that security measures are in force, but it does no actual protection on its own (because people can disable JavaScript). JavaScript does support regular expressions, although only in more recent versions of the language. For the code to be more backward-compatible, I avoided using JavaScript regular expressions here. Online surveys claim that anywhere between 10 and 20 percent of Web users do not have JavaScript enabled in their Web browsers.
|