使用PHP表单在必填字段中苦苦挣扎

时间:2015-07-20 20:51:36

标签: php required-field

这是我第一次使用php而且我不知道我在做什么。我已经使用了这个模板并编写了一个html表单,但是它没有必要的字段,所以它可以发送一个空白的电子邮件,如果你点击提交。我希望在' name'之后出现错误消息。和'电子邮件'和'消息'输入是空的。有人可以帮忙吗?

<?php

$EmailFrom = "joejlomax@gmail.com";
$EmailTo = "joejlomax@gmail.com";
$Subject = "T/V/C Inquiry";
$Name = Trim(stripslashes($_POST['Name'])); 
$Tel = Trim(stripslashes($_POST['Tel'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Message = Trim(stripslashes($_POST['Message'])); 


// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
}
?>

1 个答案:

答案 0 :(得分:0)

您可以使用empty检查变量是否为空。

$validationOK = true;
if(empty($Name) OR empty($Tel) OR empty($Email) OR empty($Message)) {
    $validationOK = false;
}
if (!$validationOK) {
    print "<meta http-equiv=\"refresh\" content=\"0;URL=error.php\">";
    exit;
}