Using JavaScript to Validate Data


Here's another option to consider when validating user dataJavaScript. Using JavaScript lets you check user data in the browser before it has to be sent back to the server to be checked. You save time by not requiring a roundtrip to the server, and you save demand on the server. This isn't a PHP topic, but it's worth a look. (Note that you might also validate on the server as well, in case the user has JavaScript turned off.)

Here's an example, where we'll check if a date the user is submitting is in the format 12/31/05 or 12/31/2005and if not, we'll display an error, stopping the form from being submitted until it's fixed. To check the data, we'll write a JavaScript function named checker. When the form is submitted, we'll have JavaScript call that function:

 <FORM NAME="form1" ACTION="somepage.php" METHOD="POST"     ONSUBMIT="return checker()">     Please enter a date:     <INPUT TYPE="TEXT" NAME="text1">     <INPUT TYPE="SUBMIT" value="Submit"> </FORM> 

JavaScript can handle regular expressions, so the checker function will use them to check the format of the submitted date, as you see in phpjavascript.html, Example 6-16. You don't have to use regular expressions, of course; you could check numerical ranges, whether or not the user entered any data at all, and so on.

Example 6-16. A JavaScript example, phpjavascript.html
 <HTML>     <HEAD>         <TITLE>Verifying User Data</TITLE>         <SCRIPT LANGUAGE="JavaScript">             <!--             function checker()             {                 var regExp1 = /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/                 var regExp2 = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/                 var result1 = document.form1.text1.value.match(regExp1)                 var result2 = document.form1.text1.value.match(regExp2)                 if (result1 == null && result2 == null) {                     alert("Sorry, that's not a valid date.")                     document.form1.text1.value = ""                     return false                 } else {                     document.form1.submit()                 }             }             //-->         </SCRIPT>     </HEAD>     <BODY>         <H1>Verifying User Data</H1>         <FORM NAME="form1" ACTION="somepage.php" METHOD="POST"             ONSUBMIT="return checker()">             Please enter a date:             <INPUT TYPE="TEXT" NAME="text1">             <INPUT TYPE="SUBMIT" value="Submit">         </FORM>     </BODY> <HTML> 

You can see how this works in Figure 6-21, where the user has entered a date that's not formatted the way we want it.

Figure 6-21. Checking user data.


When the user clicks the Submit button, he or she will see the error message box in Figure 6-22.

Figure 6-22. Giving error feedback.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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