Form Validation using PHP
Posted: Fri Nov 20, 2009 4:01 pm
Hi, I'm new to PHP and I really don' know where to even start. I have to validate a form on my website. The form contains many fields and all fields are required and I should have an error message that will appear if they are not complete or completed incorrectly. I also have to make sure that the phone number is ###-###-#### format and the email is xxx@xxxxxx.xxx format.
When the form is successfully completed there should be a confirmation page with the information on it and a thank you message. The entered info should be written to a text file and emails should be sent to myself and the visitor. The visitor's email should be a confirmation email requiring a reply.
I've been searching for help but I don't even understand the basic code.
I found something I thought may work so I tried it but I was not successful with it. Here's the code I tried to use. It was only checking the fields to make sure they were not empty...but it still allowed the form to be processed with empty fields.
When the form is successfully completed there should be a confirmation page with the information on it and a thank you message. The entered info should be written to a text file and emails should be sent to myself and the visitor. The visitor's email should be a confirmation email requiring a reply.
I've been searching for help but I don't even understand the basic code.
I found something I thought may work so I tried it but I was not successful with it. Here's the code I tried to use. It was only checking the fields to make sure they were not empty...but it still allowed the form to be processed with empty fields.
Code: Select all
<?
If (empty($_POST['fname']))
{
$errors[] = 'Please enter a first name';
}
If (empty($_POST['lname']))
{
$errors[] = 'Please enter a last name';
}
If (empty($_POST['title']))
{
$errors[] = 'Please enter a job title';
}
If (empty($_POST['company']))
{
$errors[] = 'Please enter your company name';
}
If (empty($_POST['address']))
{
$errors[] = 'Please enter your mailing address';
}
If (empty($_POST['city']))
{
$errors[] = 'Please enter your city';
}
If (empty($_POST['zip']))
{
$errors[] = 'Please enter your zip code';
}
If (empty($_POST['state']))
{
$errors[] = 'Please enter your state';
}
If (empty($_POST['phone']))
{
$errors[] = 'Please enter your phone number';
}
If (empty($_POST['fax']))
{
$errors[] = 'Please enter a fax number';
}
If (empty($_POST['email']))
{
$errors[] = 'Please enter your email address';
}
else if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_POST['email']))
{
$errors[] = 'Please enter a valid e-mail address';
}
if (count($errors) == 0)
{
// Process form
}
else
{
echo $errors[0];
}
?>