2013-08-29 61 views
1

我有一个联系表,我需要在PHP中验证以检查每个字段是否被正确填充。在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 [email protected]'); 
    window.location = 'contact.html'; 
</script> 
<?php 
} 
?> 

这什么也不做,当我试图提交一个空的接触形式,它应该提醒特定领域,其没有填补的用户,但事实并非如此。它只是把我带到一个空白的白页。

任何人都可以帮我找到我要去的地方吗?

+0

开始发送邮件之前进行任何验证 – 2013-08-29 22:34:51

+0

空白页?你的错误日志说什么? – James

回答

1

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

例子:

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

是的,这工作正常。我的表单验证工作。谢谢:) –

+0

+ =正在工作:O,它不应该工作 –

+0

不,我把它改成'。='就像你说的那样。 –

1

而是变量,空字符串这样$field_services == ''比较,使用empty()isset()

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

的另一个问题是,您连接使用+字符串,如果您使用的是javascript,javaC#等。不是PHP

要使用PHP串联变量:

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

echo $var;// Hello World ! 

所以,你的代码应该是:

if(empty($_POST['name'])){ 
    $errormessage .= 'You have not entered your Name\n'; 
} 
+0

是的:p也习惯JavaScript ...'。='它是 –

1

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

2

此外,您可以使用修剪功能删除任何空间。

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