![](/img/trans.png)
[英]How to validate contact form required fields and display the error message accordingly
[英]Validating all the fields to display the error message in Contact Form in PHP
如果我單擊“提交”按鈕,則需要包含多個錯誤。 如果用戶未填寫所有必填字段,則錯誤應顯示在表單頂部。當前,當我單擊“提交”按鈕時,錯誤指向“注釋”行,並且僅顯示“注釋”錯誤
我用了- $error=$error."<br/> or $error.="<br />
它們都不如預期那樣工作
如何用和錯誤信息顯示我的所有字段? 我的代碼如下所示
<?php
if ($_POST["submit"]) {
if($_POST['email']) {
$error="<br/>Please enter your Email address";
}
if($_POST['dest']) {
$error.="<br/>Please enter your Destination Name ";
}
if($_POST['dcity']) {
$error.="<br/>Please enter your Departure City ";
}
if($_POST['name']) {
$error.="<br/>Please enter your Name ";
}
if($_POST['cnum']) {
$error.="<br/>Please enter your Contact Number";
}
if($_POST['adults']) {
$error.="<br/>Please enter Number Of Adults";
}
if($_POST['child']) {
$error.="<br/>Please enter Number Of Children";
}
if($_POST['comment']) {
$error.="<br/>Please enter Your Comments ";
}
if ($error){
$result='<div class="alert alert-danger"><strong>There were error(s) in your form:</strong>' .$error.' </div>';
}
}
?>
首先,您應該正確檢查字段是否為空,如下所示:
if(empty($_POST['email'])) {
您的代碼實際上是相反的,如果變量為true(-ish),則當前條件已匹配。 在任何情況下,為了避免警告,請使用empty()
或!empty()
-如果是POST數據; 否則也為isset()
等isset()
而不是直接測試可能存在或可能不存在的變量。
其次,您應該:使用數組匯總錯誤: $error = []; ... $error[] = 'This error';
$error = []; ... $error[] = 'This error';
-或者:首先定義一個空字符串, $error = '';
嘗試與.=
連接之前。 就目前而言,您的代碼僅在未設置email
字段的情況下定義錯誤變量。 使用數組也可以避免<br />
串聯的麻煩; 只是implode('<br />', $error)
。
編輯:如果您想擺脫所有的重復檢查和冗余代碼,並在將來使您的應用程序更容易擴展,則可以對內容進行抽象化並執行以下操作:
$err_msgs = [
'email' => 'your Email address',
'dest' => 'your Destination Name',
'dcity' => 'your Departure City',
'name' => 'your Name',
'cnum' => 'your Contact Number',
'adults' => 'Number Of Adults',
'child' => 'Number Of Children',
'comment' => 'your Comments',
];
$errors = [];
foreach($err_msgs as $key => $msg) {
if (empty($_POST[$key])) {
$errors[] = 'Please enter ' . $msg;
}
}
if (count($errors) > 0) { // OR: if (!empty($errors)) {
$result = '<div class="alert alert-danger"><strong>
There were error(s) in your form:</strong><br />'
. implode('<br />', $errors)
. ' </div>';
}
這里發生的事情:我們在數組中將所有期望的字段及其唯一錯誤消息定義為鍵/消息對,這些鍵與表單字段的名稱相同。 然后,我們遍歷數組並檢查空字段,並在一處生成所有錯誤消息,並將它們添加到數組中。 最后,如果$errors
數組包含消息,我們將它們打印出來。
最佳解決方案:分配一個空字符串: $error = '';
然后將其連接起來。 即
if($_POST['some_key']){
$error .= 'this is an error';
}
//...
if($error != '') {
echo $error;
}
我認為您遇到的問題是由於一個案例:
如果存在電子郵件,則此后將連接什么$error
。
但是像往常一樣,我們驗證如下所示:
if(isset($_POST['some_key']) && empty(trim($_POST['some_key']) {
//put error string here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.