One easy way to check if the user has entered a number is to convert the submitted text to a number (using PHP functions such as intval or floatval) and then back to a string (with the strval function), and compare the result with the original text. If the two are equal, the original text held a number. Here's what that might look like (the strcmp function returns a non-zero value if the strings you're comparing are different): function validate_data() { global $errors; if(strcmp($_REQUEST["Number"], strval(intval($_REQUEST["Number"])))) { $errors[] = "<FONT COLOR='RED'>Please enter an integer</FONT>"; } } All that's left is to display any errors and create the welcome page, as shown in phpinteger.php, Example 6-11. Example 6-11. Requiring integer input, phpinteger.php<HTML><HEAD><TITLE>Checking for Integers</TITLE></HEAD> <BODY><CENTER><H1>Checking for Integers</H1> <?php $errors = array(); if(isset($_REQUEST["seen_already"])){ validate_data(); if(count($errors) != 0){ display_errors(); display_welcome(); } else {_data();} } else { display_welcome(); } function validate_data() { global $errors; if(strcmp($_REQUEST["Number"], strval(intval($_REQUEST["Number"])))) { $errors[] = "<FONT COLOR='RED'>Please enter an integer</FONT>"; } } function display_errors() { global $errors; foreach ($errors as $err){echo $err, "<BR>";} } function process_data() { echo "Your integer is "; echo $_REQUEST["Number"]; } function display_welcome() { echo "<FORM METHOD='POST' ACTION='phpinteger.php'>"; echo "Please enter an integer."; echo "<BR>"; echo "<INPUT NAME='Number' 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> You can see an example where the user didn't enter an integer in Figure 6-14. Figure 6-14. Checking for numbers. |