Email 格式驗證是表單處理必備。本文詳細說明 PHP 內建驗證、正則表達式進階模式、常見錯誤模式與最佳實踐,幫助你建立既嚴格又實用的驗證邏輯。
<?php
function validateEmail($email) {
// 基本格式驗證
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
// 額外檢查:長度限制 (RFC 5321: local-part <= 64, domain <= 255, total <= 254)
if (strlen($email) > 254) return false;
[$local, $domain] = explode('@', $email);
if (strlen($local) > 64 || strlen($domain) > 255) return false;
// 選擇性:檢查域名是否有 MX 記錄 (見下節)
// if (!checkdnsrr($domain, 'MX') && !checkdnsrr($domain, 'A')) return false;
return true;
}
// 測試
$tests = [
'user@example.com' => true,
'user.name@domain.com' => true,
'user+tag@sub.domain.com'=> true,
'user@localhost' => false, // 無 TLD,filter_var 會通過但實際不可用
'user@com' => false,
'@domain.com' => false,
'user@' => false,
'user@domain..com' => false,
'user name@domain.com' => false,
];
foreach ($tests as $email => $expected) {
$result = validateEmail($email);
$status = $result === $expected ? '✅' : '❌';
echo "$status $email => " . ($result ? '通過' : '失敗') . "<br>";
}
?>
<?php
// 這是簡化版,涵蓋 99.9% 實際使用案例
$pattern = '/
^ # 開頭
[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+ # local-part: 允許字元
@ # @ 符號
[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])? # domain label 1
(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+ # 後續 labels
$ # 結尾
/x';
function validateEmailRegex($email) {
global $pattern;
return (bool)preg_match($pattern, $email);
}
?>
| 正則 | 特點 | 問題 |
|---|---|---|
/^.+@.+\..+$/ | 最簡單 | 允許 'a@b.c'、'@domain.com'、多個 @、空白等 |
/^[\w.-]+@[\w.-]+\.\w+$/ | 常見簡化 | 不支援 +tag、連續點、Unicode、過長 |
/^[^@\s]+@[^@\s]+\.[^@\s]+$/ | 排除空白與 @ | 同樣不支援 RFC 完整規範 |
| filter_var | 內建、維護由 PHP 團隊負責 | 兜許部分技術合法但實際少用格式 (如 quoted-string、IP 域名) |
<?php
function validateEmailWithDns($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
$domain = explode('@', $email)[1];
// 檢查 MX 記錄 (郵件伺服器)
if (checkdnsrr($domain, 'MX')) return true;
// Fallback: 檢查 A 記錄 (無 MX 時直接解析 IP)
if (checkdnsrr($domain, 'A')) return true;
return false;
}
// 快取 DNS 查詢結果避免重複查詢
function validateEmailCached($email, &$cache = []) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
$domain = explode('@', $email)[1];
if (!isset($cache[$domain])) {
$cache[$domain] = checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A');
}
return $cache[$domain];
}
?>
透過 SMTP RCPT TO 指令驗證帳號存在,但有灰名單、IP 封鎖、Catch-all 等限制,不建議在註冊流程同步呼叫。
<!-- HTML5 內建驗證 -->
<form>
<input type="email" name="email" required
pattern="[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"
title="請輸入有效 Email 格式">
<input type="submit">
</form>
<script>
// JavaScript 即時檢查
document.querySelector('input[type="email"]').addEventListener('blur', function() {
if (!this.checkValidity()) {
this.setCustomValidity('Email 格式不正確');
} else {
this.setCustomValidity('');
}
});
</script>
<?php
function validateEmailComplete($email, $checkDns = true) {
// 1. 基本清理
$email = trim($email);
if ($email === '') return ['valid' => false, 'reason' => 'empty'];
// 2. 格式驗證
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return ['valid' => false, 'reason' => 'format'];
}
// 3. 長度檢查
if (strlen($email) > 254) {
return ['valid' => false, 'reason' => 'too_long'];
}
[$local, $domain] = explode('@', $email);
if (strlen($local) > 64 || strlen($domain) > 255) {
return ['valid' => false, 'reason' => 'part_too_long'];
}
// 4. 域名存在性 (可選,註冊時建議開啟)
if ($checkDns) {
if (!checkdnsrr($domain, 'MX') && !checkdnsrr($domain, 'A')) {
return ['valid' => false, 'reason' => 'domain_not_found'];
}
}
// 5. 黑名單檢查 (一次性信箱、垃圾郵件域名)
$disposable = ['mailinator.com', '10minutemail.com', 'guerrillamail.com', 'tempmail.com'];
if (in_array(strtolower($domain), $disposable)) {
return ['valid' => false, 'reason' => 'disposable'];
}
return ['valid' => true, 'reason' => 'ok'];
}
// 使用
$result = validateEmailComplete($_POST['email'] ?? '');
if (!$result['valid']) {
$messages = [
'empty' => '請輸入 Email',
'format' => 'Email 格式不正確',
'too_long' => 'Email 過長',
'part_too_long' => 'Email 部分過長',
'domain_not_found' => '域名不存在或無法接收郵件',
'disposable' => '不接受一次性信箱',
];
echo $messages[$result['reason']] ?? '驗證失敗';
}
?>
| 錯誤輸入 | filter_var | 建議處理 |
|---|---|---|
| user@domain | ✅ 通過 | 加上 DNS 檢查或要求 TLD |
| user@192.168.1.1 | ✅ 通過 (IP 域名合法) | 通常拒絕 IP 域名 |
| "user name"@domain.com | ✅ 通過 (quoted-string) | 極少見,可接受或拒絕 |
| user@[IPv6:2001:db8::1] | ✅ 通過 | 極少見,通常拒絕 |
| user@domain..com | ❌ 失敗 | 正確拒絕 |