[英]Problems Validating Form With PHP
我正在为我的网站编写一份简短的联系表,但遇到一些问题。 一切都可以正常显示,但是除了未定义变量的通知(因为我使用$ post [$ value]将数据保留在表单输入中)之外,验证完全不再起作用。 我已经将其与之前编写的功能代码进行了比较,但是没有发现任何明显的不同。 这是表格的代码:
<?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>
这是验证它的代码。
<?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";
}
您可以使用AJAX将表单数据提交到PHP脚本。 在这种情况下,您可以将验证或成功结果作为JSON并将其付诸实践。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.