【发布时间】:2014-08-10 04:05:09
【问题描述】:
我有以下简单的表单,我正在尝试获取电子邮件验证错误 在提交之前显示在表单中以显示错误。
有没有办法用 PHP 做到这一点,还是我必须使用 JSON?
如果我必须使用 JSON,谁能告诉我如何做到这一点?
提前致谢。
form.html:
<form method="post" name="form" action="form.php">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<div id="error"></div>
form.php
<?php
// send to and from
$to = "email@example.com";
$headers = "From: email@example.com \r\n";
$headers .= "Reply-To: email@example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body =
"A message from your website contact form \n\n".
"Email: $email \n\n".
"Phone: $phone \n\n".
"From: $name \n\n".
"Message: \n".
"$message \n";
// honeypot
if($robot)
header( "Location: http://www.example.com/nothankyou.html" );
else{
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '<div id="error">Please Enter a Valid Email</div>';
}
else
{
// send it
mail($to,$email_subject,$email_body,$headers);
header( "Location: http://www.example.com/thankyou.html" );
}
}
?>
【问题讨论】:
-
你可以使用 JS/Ajax。那里有很多工作演示。
-
如果您在提交之前进行验证,您将不会使用 JSON。您将通过 javascript 检查值,然后在验证完成后将数据转换为 json 以发送到您的操作中。
-
我已经准备了 JS 验证器,所以你可以尝试使用它,也许它可以帮助你轻松解决问题 :) github.com/softdream/wfvalidator
标签: javascript php jquery json forms