我如何制作"电子邮件"字段不是必须的?即使某人没有填写该字段,表格也应提交。
在下面的代码中,"电子邮件"字段是强制性的。
我尝试添加!isset
电子邮件字段,以便$email_from
得到“#34;空白”字样,但它对我不起作用。
<?php
if(isset($_POST['name'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "aaaaa@aaaaa.com";
$email_subject = "Messeage from your site";
function died($error) {
?>
<?php
die();
}
// validation expected data exists
if(!isset($_POST['name']) ||
//!isset($_POST['email']) || /* i tried to comment this line, but didnt work. */
!isset($_POST['telephone']))
{
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
// create email headers
$headers = 'מאת: '.$email_from."\r\n".
'חזור ל: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<?php
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=thank_you.html">';
exit;
?>
<?php
}
?>
答案 0 :(得分:1)
if(!isset($_POST['name']) ||
!isset($_POST['telephone'])){
if(isset($_POST['email'])){
//all code for email inside here
}
}
这应该是技巧,而$ _POST ['email']是空的,它不应该打扰你了。
答案 1 :(得分:1)
preg_match
上的$email_form
使其成为必需。
如果您首先检查是否设置了$email_form
,并且执行preg_match
它必须有效。
像这样:
if(!empty($_POST['email'])){
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br/>';
}
} else {
$email_from = '';
}
答案 2 :(得分:0)
我做了,而且有效:
if(!empty($_POST['email'])){
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
}
答案 3 :(得分:0)
使用php5中的FILTER_VALIDATE_EMAIL检查电子邮件是否有效
if(isset($_POST['email']))
{
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $email." E-mail is not valid.";
}
else
{
echo $email." E-mail is valid.";
}
}