在PHP中验证联系表单

时间:2013-08-29 22:31:47

标签: php html validation contact-form

我有一个联系表单,我需要在PHP中验证以检查每个字段是否正确填充。

这就是我所拥有的:

//Post fields
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_services = $_POST['services'];
$field_it = $_POST['it'];
$field_location = $_POST['location'];
$field_message = $_POST['message'];


//mail_to omitted 


//Validation of contact form

$errormessage = '';
if($field_name == ''){

$errormessage += 'You have not entered your Name\n';
}

if($field_email == ''){

$errormessage += 'You have not entered your Email Address\n';
}

if($field_services == ''){

$errormessage += 'You have not chosen the service you require\n';
}

if($field_it == ''){

$errormessage += 'You have not chosen the Date of your event\n';
}

if($field_location == ''){

$errormessage += 'You have not entered the location of your event\n';
}


if($errormessage != ''){ ?>

<script language="javascript" type="text/javascript">
    alert('The following fields have not neen entered correctly\n<?php echo "$errormessage" ?>');
    window.location = 'contact.html';
</script>
<?php } 



if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
    alert('Thank you for the message. We will contact you shortly.');
    window.location = 'contact.html';
</script>
<?php
}


else { ?>
<script language="javascript" type="text/javascript">
    alert('Message failed. Please, send an email to s_ejaz@live.co.uk');
    window.location = 'contact.html';
</script>
<?php
}
?>

当我尝试提交一个空的联系表单时,这没有任何作用,它应该提醒用户未填写但未填写的特定字段。它只是带我一个空白的白页。

有人能帮我找到我错的地方吗?

4 个答案:

答案 0 :(得分:2)

此外,您可以使用trim功能删除任何空格。

trim($_POST['name'])...

答案 1 :(得分:1)

您应该使用strlen()isset()来检查是否从表单中收到任何数据。

示例:

if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
    $errormessage .= 'You have not entered your Name\n';
}

答案 2 :(得分:1)

使用empty()isset()

,而不是像$field_services == ''那样将变量与空字符串进行比较

if(!empty($field_services))if(isset($field_services))

另一个问题是您使用+连接字符串,如果您使用的是javascriptjavaC#等,则为真。{{1} }。

使用PHP连接变量:

PHP

所以您的代码应为:

 $var='Hello';
 $var.=' World !'

 echo $var;// Hello World !

答案 3 :(得分:1)

尝试使用$errormessage.='Some text\n';代替$errormessage+='Some text\n'; 使用“+”而不是“.”,PHP将变量$errormessage视为数字,并且断言失败。

相关问题