Validating Data: Requiring Data Entry


One of the most common types of data validation is to make sure that the user entered some required data. For example, say your application has a text field called "Name" that you want the user to enter his or her name in, as shown in Figure 6-11. If the user entered his or her name, that name is displayed, as you see in Figure 6-12.

Figure 6-11. Validating data.


Figure 6-12. Handling correct data.


But what if the user didn't enter anything in the text field? We'll check that when we validate the form in our validate_data function. If there's no text in the "Name" text field, we'll add an error to our $errors array like this, using red text in HTML:

 function validate_data() {     global $errors;     if($_REQUEST["Name"] == "") {         $errors[] = "<FONT COLOR='RED'>Please enter your             name</FONT>";     } } 

All that's left is to customize the code in the process_data function to display the name the user entered and the code in the display_welcome function to display the text field and prompt "What's your name?" to the user. You can see how that works in the entire web application, phpvalidate.php, Example 6-10.

Example 6-10. Requiring text entry, phpvalidate.php
 <HTML><HEAD><TITLE>Using Text Fields</TITLE></HEAD>     <BODY><CENTER>                 <H1>Using Text Fields</H1>         <?php             $errors = array();             if(isset($_REQUEST["seen_already"])){                 validate_data();                 if(count($errors) != 0){                     display_errors();                     display_welcome();                 }                 else {                     process_data();                 }             }             else {                 display_welcome();             }         .         .         .             function display_welcome()             {                 echo "<FORM METHOD='POST' ACTION='phpvalidate.php'>";                 echo "What's your name?";                 echo "<BR>";                 echo "<INPUT NAME='Name' TYPE='TEXT'>";                 echo "<BR>";                 echo "<BR>";                 echo "<INPUT TYPE='SUBMIT' VALUE='Submit'>";                 echo "<INPUT TYPE='HIDDEN' NAME='seen_already'                     VALUE='hidden_data'>";                 echo "</FORM>";             }         ?>         </CENTER></BODY></HTML> 

Now if the user doesn't enter anything in the text field, he or she will see an error message in red (shown in glorious black and white in the figure, though) in Figure 6-13.

Figure 6-13. Handling a validation error.




    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