2011-11-14 51 views
0

我有一個聯繫頁面上的HTML表單域,然後將數據發送到一個php頁面。xhtml所需的聯繫表單字段?

如果用戶沒有輸入值,我想使表單字段爲必填項,並在標籤旁邊顯示紅色(*)。

我該怎麼做?

<form id="contact_form" method="post" action="contact.php"> 

    <p style="margin-top:20px"> 
     <label for="title">Title</label><br/> 
     <input id="your_name" name="your_name" type="text" style="width:94%"/> 
    </p> 

    <p style="margin-top:20px"> 
     <label for="initial">Initial</label><br/> 
     <input id="initial" name="initial" type="text" style="width:94%"/> 
    </p> 
    <p style="margin-top:20px"> 
     <label for="surname">Surname</label><br/> 
     <input id="surname" name="surname" type="text" style="width:94%"/> 
    </p> 
     <p style="margin-top:20px"> 
     <label for="tel_number">Tel number</label><br/> 
     <input id="tel_number" name="tel_number" type="text" style="width:94%"/> 
    </p> 
    <p style="margin-top:20px"> 
     <label for="email">Email</label><br/> 
     <input id="email" name="email" type="text" style="width:94%"/> 
    </p> 

    <p style="margin-top:20px"> 
     <label for="enquiry">Enquiry</label><br/> 
     <textarea id="enquiry" name="enquiry" rows="7" cols="10" style="width:94%"></textarea> 
    </p> 

    <p style="margin-top:50px"> 
     <input type="submit" value="Send Message"/><br/> 
    </p> 

</form> 
+0

您已經標記了這個jQuery。你有沒有嘗試過基於jQuery的驗證庫? – Rup

回答

0

你將不得不把形式的PHP文件(或.phtml推薦*)。添加一個css類,如.input-error

.input-error { color: red; } 

在你的表格,你需要這樣的事每個字段:

if (empty($postData['field']) { 
    echo "<span class=\"input-error\">*</span>"; 
} 

爲了給出一個明確的例子:

<p style="margin-top:20px"> 
    <?php if (empty($postData['your_name']): ?> 
     <span class="input-error">*</span> 
    <?php endif; ?> 
    <label for="title">Title</label><br/> 
    <input id="your_name" name="your_name" type="text" style="width:94%"/> 
</p> 

的形式將要提交給一個將處理表單並將您帶回此頁面的php文件。在該文件中你需要這樣一行:

$postData = $_POST; 

或者,如果該腳本重定向到另一個頁面,那麼你就需要到後期數據存儲在會話中。像:

$_SESSION['postData'] = $_POST; 

在這種情況下,在窗體的頂部或控制器的地方(如果有的話),提取數據,就像這樣:

$postData = $_SESSION['postData'];