|
How can we validate a form using Php? |
I'm just writing a small script about how you can validate a form using
php.This question i use to get daily in my inbox.so i thought ,i should post
this script in my site.that might be very helpful for new comers.
My html page consisting of a form.and i want to validate
all the fields of that form.i have three input field in that
form(name,email,address).
here is my html page,
-------------------------------
example.htm
-------------------------------
<html>
<body>
<center></center><b>Simple Form Validation</b></center>
<pre>
Enter following details:
(all the fields are required).
<form method="post" action="submit.php3">
Name <input type="Text" name="name">
Email <input type="Text" name="email">
Address <input type="Text" name="address">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
------------------------
Now after clicking on submit button the data will be submitting to
"submit.php" and process it. if the user has not entered the required
fields then we have to show him an error message otherwise the record should
store in the database..
-------------------------
Here is the 'submit.php'
-------------------------
<html>
<body>
<?
if (isset($submit)){
//when user clicks on submit button
if (!$name | | !$email | | !$address){
//if user is not entering any of the above field then show
//him an error message
echo "<b><font color="#FF0000">Error!! </font></b>\n";
echo "You have not entered the following field(s).\n";
echo "<a href="#" onclick="history.back();"><i>
Hit back and try again</i></a>.</font>
n";
$fields_to_validate=array('name','email','address');
//validate above fields.
$field_display_value=array('Name','Email','Address');
//if the field is not set then show the above display value.
//make sure that the display value order is same as
//$fields_to_validate array.
echo "<ul>\n";
for($a=0;$a<count($fields_to_validate);$a++){
//loop through fields and check wether that has been set or not.
if(!${$fields_to_validate[$a]}){
//check wether the required fields are entered or not.
echo "<li><font color="#FF0000">$field_display_value[$a]</font>\n";
}
}
echo "</ul>n";
//next check wether email address is valid or not.
}elseif(!eregi('^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+.)*([a-z0-9-]+)
(.[a-z]{2,3}))$', $email)){
//invalid email address
echo "<font color="#FF0000"><b>Error-</b> </font>Invalid Email !!\n";
echo "<a href="#" onClick="history.back();"><b> Go back </b></a>
and Try again.\n";
}else{
//yes,user has filled the form..and it is valid..
//so save the record here and show him a message..
echo "Thank you $name!!,your record saved successfully\n"; }
}else{
//user has not clicked on submit button.so show him
//access denied message.
echo "Error!! Access Denied\n";
exit;
}
?>
</body>
</html>
-----------------
You can modify above script and use it for your form validations.
Thank you
|
|
Author: S Rajan |
|
Send any comments at: info@lizratechnologies.com
|