PHP 表單 - 驗證電子郵件和 URL
本章介紹瞭如何驗證姓名、電子郵件和 URL。
PHP - 驗證姓名
下面的程式碼展示了一種簡單的方法來檢查姓名欄位是否只包含字母、破折號、撇號和空格。如果姓名欄位的值無效,則儲存錯誤訊息。
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
preg_match()
函式在字串中搜索模式,如果模式存在則返回 true,否則返回 false。
PHP - 驗證電子郵件
檢查電子郵件地址是否格式正確的簡便安全的方法是使用 PHP 的 filter_var()
函式。
在下面的程式碼中,如果電子郵件地址格式不正確,則儲存錯誤訊息。
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - 驗證 URL
下面的程式碼展示了一種檢查 URL 地址語法是否有效的方法(此正則表示式也允許 URL 中包含破折號)。如果 URL 地址語法無效,則儲存錯誤訊息。
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
PHP - 驗證姓名、電子郵件和 URL
現在,指令碼看起來像這樣:
示例
// define variables and set to empty values
$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"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the 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"]);
}
}
執行示例 »
下一步是展示如何防止使用者提交表單時清空所有輸入欄位。