2013-08-29 77 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'])...