PHP 表單驗證 - 驗證 E-mail 和 URL
PHP 表單必填
PHP 表單完成
本節展示如何驗證名字、電郵和 URL。
PHP - 驗證名字
以下代碼展示的簡單方法檢查 name 欄位是否包含字母和空格。如果 name 欄位無效,則儲存一條錯誤訊息:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "只允許字母和空格!";
}
注釋:preg_match() 函數檢索字串的模式,如果模式存在則返回 true,否則返回 false。
PHP - 驗證 E-mail
以下代碼展示的簡單方法檢查 e-mail 地址文法是否有效。如果無效則儲存一條錯誤訊息:
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "無效的 email 格式!";
}
PHP - 驗證 URL
以下代碼展示的方法檢查 URL 地址文法是否有效(這條Regex同時允許 URL 中的斜杠)。如果 URL 地址文法無效,則儲存一條錯誤訊息:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%
=~_|]/i",$website)) {
$websiteErr = "無效的 URL";
}
PHP - 驗證 Name、E-mail、以及 URL
現在,指令碼是這樣的:
執行個體
<?php// 定義變數並設定為空白值$nameErr = $emailErr = $genderErr = $websiteErr = "";$name = $email = $gender = $comment = $website = "";if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // 檢查名字是否包含字母和空格 if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // 檢查電郵地址文法是否有效 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // 檢查 URL 地址語言是否有效(此Regex同樣允許 URL 中的底線) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/% =~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); }}?>