Section 15.1. Validating User Input with JavaScript


15.1. Validating User Input with JavaScript

On the client side, your best tool for validating data is JavaScript. JavaScript is different than PHP, because it's designed to execute in the user's browser instead of on the server. Because it executes in the client's computer, JavaScript is not allowed to access anything that could be a security risk, such as the local filesystem or network resources. JavaScript is primarily used in web pages. Although its name sounds like Java, it has no relationship to it.

Since this processing is built into most modern browsers, it's not difficult for end users to disable it. Therefore, even when you use JavaScript, always take precautions to handle the possibility of it not being present on the browser.

Some of the practical things you can do with JavaScript are checking fields and alerting the user to a problem before the data is submitted to the server. The validation can be as simple as checking for an empty field or more complex checks such as validating an email address.

Although JavaScript provides immediate feedback to a user if a field doesn't pass validation, it shouldn't be relied upon as the only validation method. Your PHP code should always perform the final validation.


JavaScript has many functions built in for validating fields. They range from the familiar length function to more complex and powerful regular expressions. We'll discuss regular expressions in more detail later. For now, all you need to know is that they provide a way of concisely describing what a string should look like. For example, an email address should have an at (@) sign with alphanumeric characters before and after it, such as michele@krautgrrl.com.

There is one non-JavaScript tactic you can use to reduce client-side errors. You can set the MAXLENGTH attribute in your form's text fields. This prevents users from entering strings that are too large.

Let's go ahead and work with Example 15-1, which validates before submission.

Example 15-1. Building a form that validates its fields before submission

 <SCRIPT LANGUAGE="JavaScript1.2" src="/books/2/233/1/html/2/source.js"> </SCRIPT> <HTML> <HEAD>     <TITLE>Sample Form</TITLE> </HEAD> <SCRIPT LANGUAGE="JavaScript1.2">     function check_valid(form) {     var error = "";     error += verify_username(form.username.value);     error += verify_password(form.password.value);     error += verify_phone(form.phone.value);     error += verify_email(form.email.value);     if (error != "") {        alert(error);        return false;     } return true; } </SCRIPT> <BODY BGCOLOR="#FFFFFF">     <FORM action="process.php" METHOD="post" onSubmit="return check_valid(this)"  name="test1">     <TABLE BORDER="0" WIDTH="100%" CELLSPACING="0" CELLPADDING="0">         <TR>             <TD WIDTH="30%" ALIGN="right">Username</TD>             <TD WIDTH="70%">: <INPUT TYPE="text" NAME="username"></TD>         </TR>         <TR>             <TD ALIGN="right">Password</TD>             <TD>: <INPUT TYPE="password" NAME="password"></TD>         </TR>         <TR>             <TD ALIGN="right">Phone</TD>             <TD>: <INPUT TYPE="phone" NAME="phone"></TD>         </TR>         <TR>             <TD ALIGN="right">Email</TD>             <TD>: <INPUT TYPE="email" NAME="email"></TD>         </TR>         <TR>             <TD>&nbsp;</TD>             <TD><INPUT TYPE="SUBMIT" VALUE="Submit"></TD>         </TR>     </TABLE>     </FORM> </BODY> </HTML> 

Example 15-1 includes the JavaScript in Example 15-2. The SRC= tag within the SCRIPT element includes the script that makes the functions available within the HTML source file.

Example 15-2. The file source.js contains functions to check the various fields

 // verify username - 610 chars, uc, lc, and underscore only. function verify_username (strng) { var error = ""; if (strng == "") {    error = "You didn't enter a username.\n"; }     var illegalChars = /\W/; // allow letters, numbers, and underscores     if ((strng.length < 6) || (strng.length > 10)) {        error = "The username is the wrong length. It must be 6-10 characters.\n";     }     else if (illegalChars.test(strng)) {     error = "The username contains illegal characters.\n";     } return error; } // verify password - between 68 chars, uppercase, lowercase, and numeral function verify_password (strng) { var error = ""; if (strng == "") {    error = "You didn't enter a password.\n"; }     var illegalChars = /[\W_]/; // allow only letters and numbers     if ((strng.length < 6) || (strng.length > 8)) {        error = "The password is the wrong length. It must be 68 characters.\n";     }     else if (illegalChars.test(strng)) {       error = "The password contains illegal characters.\n";     }     else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {        error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";     } return error; } // verify email function verify_email (strng) { var error=""; if (strng == "") {    error = "You didn't enter an email address.\n"; }     var emailFilter=/^.+@.+\..{2,3}$/;     if (!(emailFilter.test(strng))) {        error = "Please enter a valid email address.\n";     }     else { //test email for illegal characters        var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/          if (strng.match(illegalChars)) {           error = "The email address contains illegal characters.\n";        }     } return error; } // verify phone number - strip out delimiters and verify for 10 digits function verify_phone (strng) { var error = ""; if (strng == "") {    error = "You didn't enter a phone number.\n"; } //strip out acceptable non-numeric characters var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');     if (isNaN(parseInt(stripped))) {        error = "The phone number contains illegal characters.";     }     if (!(stripped.length == 10)) {     error = "The phone number is the wrong length. Make sure you included an area code.\n";     } return error; } 

Figure 15-1 shows a form with some invalid data, and Figure 15-2 shows the result.

Figure 15-1. Entering some invalid data into the form


Figure 15-2. The JavaScript alert window lists the validation problems




Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

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