Reputation: 323
I'm working on a short contact form for my website, but I'm having some problems. Everything displays properly, but other than notices about undefined variables (since I'm using $post[$value] to retain data in my form inputs), the validation no longer functions at all. I've compared it to functioning code that I've written before, but I'm not seeing any significant differences. Here's the code for the form:
<?php
$labels = array("first_name" => "First Name:",
"last_name" => "Last Name:",
"company" => "Company*:",
"email" => "Email:",
"phone" => "Phone Number*:",
"subject" => "Subject:",
"message" => "Message:");
$submit = "Submit";
?>
...
<?php
echo $error_message;
?>
<form method="post">
<table class="contact">
<?php
foreach($labels as $label => $field)
{
if($label != "message")
{
echo "<tr><td class='label'>$field</td>
<td class='input'><input type='text' maxlength='64' value='".$_POST[$label]."'></td>
<td class='error'>$error_array[$label]</td></tr>";
}
else {
echo "<tr><td class='label'>$field</td>
<td class='input'><textarea cols='25' rows='6'>".$_POST[$label]."</textarea></td>;
<td class='error'>$error_array[$label]</td></tr>";
}
}
echo "<tr><td class='submit'><input type='hidden' name='submitted' value='yes'>
<input type='submit' value='$submit'></td></tr>";
?>
</table>
</form>
And this is the code for validating it.
<?php
$error_message = "";
$error_array = array();
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
$name_patt = "/^[A-Za-z' -]{1,50}/";
$phone_patt = "/^[0-9)(xX -]{7,20)$/";
$addr_patt = "/^[A-Za-z0-9 .,'-]{1,50}$/";
$email_patt = "/^.+@.+\\..+$/";
if(preg_match("/first_name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array['first_name'] = "Please enter a valid first name.";
}
}
if(preg_match("/last_name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array['last_name'] = "Please enter a valid last name.";
}
}
if(preg_match("/email/i",$field))
{
if(!preg_match($email_patt,$value))
{
$error_array['email'] = "Please enter a valid email address.";
}
}
if(preg_match("/subject/i",$field))
{
if(!preg_match($addr_patt,$value))
{
$error_array['subject'] = "Please enter a subject.";
}
}
if(preg_match("/message/i",$field))
{
if(empty($_POST['message']))
{
$error_array['message'] = "Please enter a message.";
}
}
}
if(@sizeof($error_array >0))
{
include "contact.php";
$error_message = "<p class='error'>One or more fields has been filled incorrectly.</p>";
exit();
}
else
{
echo "Success!";
}
}
else
{
include "contact.php";
}
Upvotes: 0
Views: 48
Reputation: 13303
You can use AJAX to submit your form data to your PHP script. In this case you can get the validation or success result as JSON and make it into action.
Upvotes: 1