The form above requires the user to input two pieces of information, a name and an age. We know that a name consists of letters (there are some exceptions) so we need to have some kind of validation method to ensure that the name is in the correct format. Secondly, assuming that the information entered by the user will be entered into some kind of storage mechanism, we need to make sure that the data is not empty. And finally, we might want the length of the name to be eight characters maximum. The age is fairly simple. We know that the age of a person is numeric, so we expect numbers only, not letters. Assuming that the data entered by a user is going into a database, it would crash your script and possibly create a security vulnerability if the age that is entered is not a number. So it is important to check that the entered data is actually a number and not anything else. To do this we will use the is_numeric() function which checks to see if a given value is a number or not. Below is the portion of the page that puts the above in practice: <?php //validate data //1. Check if the name field is filled in: //2. Check if it is the correct length //3.Check if it is valid i.e it contains only letters if(isset($_POST['Submit'])){ $err=FALSE; $error="<ul>"; if(empty($_POST['name'])){ $err=true; $error .="<li>Please enter a name.</li>"; } if((strlen($_POST['name']))< 8){ $err=true; $error .="<li>Please enter a valid name.</li>"; } if(!eregi('^[[:alpha:].'-]{2,8}$',$_POST['name'])){ $err=TRUE; $error="<li>The name should only contain letters.</li>"; } if(empty($_POST['age'])){ $err=true; $error .="<li>Please enter a age.</li>"; } if(!is_numeric($_POST['age'])){ $err=true; $error .="<li>The age that you entered is not a number. Please check and try again</li></ul>"; } }//end submit ?>
blog comments powered by Disqus |
|
|
|
|
|
|
|