我在PHP中创建了这些表单但没有必填字段,我想强制要求姓名,电话号码和电子邮件。我该怎么做呢?
以下是代码:
<?php
$company = $_POST['company'];
$contact = $_POST['name'];
$tel = $_POST['phone'];
$email = $_POST['email'];
$comments = $_POST['message'];
$contact_type = $_POST['contact_type'];
if ($contact_type=="1")
{
$form_desc = "Contact Request Submitted";
$to_email = "mail@burlingtongroup.net, ross.crawford@burlingtongroup.net, adam.ninnis@burlingtongroup.net";
}
else if ($contact_type=="2" || $contact_type=="3")
{
$form_desc = "Call-back Request Submitted";
$to_email = "mail@burlingtongroup.net, ross.crawford@burlingtongroup.net, adam.ninnis@burlingtongroup.net";
}
else if ($contact_type=="4")
{
$form_desc = "Training Seminar Registration";
$to_email = "adam.wonnacott@burlingtongroup.com";
}
$source_page = $_SERVER['HTTP_REFERER'];
//If no errors registred, print the success message
if(isset($_POST['Submit']))
{
global $mailer;
if($contact_type=="3")
{
$content = $form_desc.", \n\n".
"Company: ".$company."\n".
"Contact: ".$contact."\n".
"Tel: ".$tel."\n".
"Email: ".$email."\n".
"Message: ".$comments."\n";
}
else if($contact_type=="4")
{
$content = $form_desc.", \n\n".
"Company: ".$company."\n".
"Contact: ".$contact."\n".
"Email: ".$email."\n";
//echo $content;
//exit;
}
else
{
$content = $form_desc.", \n\n".
"Company: ".$company."\n".
"Contact: ".$contact."\n".
"Tel: ".$tel."\n".
"Email: ".$email."\n".
"Message: ".$comments."\n";
}
mail($to_email, $form_desc.":".$company, $content, "From: ".$email );
header('Location: '.$source_page.'?sent=1');
}
?>
答案 0 :(得分:1)
最好使用客户端验证(在这种情况下,您可以为用户提供有关必填字段的热情)。从PHP方面,您可以验证如下:
if (isset($contact) && isset($tel) && isset($email)) {
// your code here
}
答案 1 :(得分:0)
您可以使用JS进行客户端验证。当然它不是PHP,但这为用户节省了时间。参考例如致:http://www.w3resource.com/javascript/form/non-empty-field.php
或者,如果您使用jQuery:jQuery: checking if the value of a field is null (empty)
答案 2 :(得分:0)
这应该有帮助......
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>