2014-05-18 23 views
0

如果字段沒有被填充,我希望我的表單顯示一個錯誤,如「輸入名字」。我有正確的代碼(我認爲)要做到這一點,但它第一次加載頁面時顯示錯誤。我希望在提交表單時顯示它。如果提交表單,則顯示錯誤

<div class="Row"> 
<div class="Lable">First Name:</div> <!--End of Lable--> 
<div class="input"> 
<input type="text" id="firstname" class="detail" name="firstname" placeholder="First Name" /> 
</div> <!--End input--> 
</div> <!--End row--> 
<span class="error">* <?php echo $nameErr;?></span> 

的PHP驗證

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
if (empty($_POST["firstname"])) { 
$nameErr = "Name is required"; 
} else { 
$firstname = test_input($_POST["name"]); 
// check if name only contains letters and whitespace 
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) { 
    $nameErr = "Only letters and white space allowed"; 
} 
} 

感謝

+1

您需要使用'isset'並將它與您的提交按鈕和/或您的'firstname'元素結合使用。 –

+0

'$ nameErr'將在第一次加載時未定義。使用'empty'或'isset' – itachi

+0

另一種選擇是使用HTML5'required'屬性。 – enapupe

回答

1

我會仔細檢查的形式PHP的JavaScript

對於JavaScript的一部分這一行添加到您的形式,因此函數validate()將表格內容之前運行將被髮送到服務器。

<form onsubmit="validate()"> 

然後你就可以添加一個SCRIPT關閉到您的文檔是這樣的:

function validate() { 
    if (/*check if fields are filled out properly*/) { 
    this.submit(); 
    } else { 
    // show message here when fields are missing 

    return false; // this line is important otherwise the form gets submitted anyway 
    } 
} 

對於PHP的一部分是不夠用isset()

這看起來像來檢查不同的充場這樣的:

$formOK = true; 
if (!isset($_POST["field-name-1"]) || $_POST["field-name-1"] == "") { 
    echo "field-1 is missing"; 
    $formOK = false 
} 
if (!isset($_POST["field-name-2"]) || $_POST["field-name-2"] == "") { 
    echo "field-2 is missing"; 
    $formOK = false 
} 

if (formOK) { 
    echo "everything is fine"; 
    // do something with your form data 
} 

雙重檢查是最好的方式,因爲首先你沒有這麼多的請求,而且javascript在反應和速度方面更加靈活,但是PHP會爲你提供保證沒有任何問題會出錯。

+0

是的,這是在發送表單之前檢查表單的一種方法。但是,您應該始終檢查一下php,以避免潛在的問題。你也可以對輸入使用'required'屬性,但這還不夠。 – blex

+0

感謝您發現我的答案以這種方式 – frieder

+0

如果我發送帶空字段的表單,您的代碼將返回「一切都很好」。因爲你用'isset'檢查字段。此方法將返回true,因爲字段IS已設置,即使它只是一個空字符串。你也應該檢查它是否等於'「」'。 – blex

0

只是嘗試:

if (isset($nameErr)) { 
    echo '<span class="error">* ' . $nameErr . '</span>'; 
} 
0

爲了應用只有在提交表單驗證,你可以檢查如果您以這種方式收到$_POST['submit']

<?php 
    $nameError=""; 

    if(isset($_POST['submit'])) 
    { 
     //validate the form 
     if(condition is not met){ $nameError="your error message"; } 
    } 
?> 

<form> 
    ... 
    <input type="text" name="firstname"/> 
    <input type="submit" name="submit"/> 
    <span class="myError">* <?=$nameError?> </span> 
</form> 

在這裏,提交按鈕將發送$_POST['submit']。開始處的錯誤消息是空的。如果有錯誤,請更改它。然後<?=$nameError?>將顯示它是否爲空。

+0

這不會解決錯誤。和'$ _SERVER ['REQUEST_METHOD']'完全沒問題。 – itachi

+0

@itachi ok,在我的編輯中添加了該功能 – blex