表單前端 (HTML5 內建驗證 + PHP 後端雙重保障)
<form method="post" action="process.php" novalidate>
<h1>聯絡資訊登錄</h1>
<table>
<tr><th><label for="nickname">暱稱</label></th>
<td><input type="text" id="nickname" name="nickname" required maxlength="20"></td></tr>
<tr><th><label for="firstname">名字</label></th>
<td><input type="text" id="firstname" name="firstname" required maxlength="30"></td></tr>
<tr><th><label for="lastname">姓氏</label></th>
<td><input type="text" id="lastname" name="lastname" required maxlength="30"></td></tr>
<tr><th><label for="email">主要 Email</label></th>
<td><input type="email" id="email" name="email" required maxlength="100"></td></tr>
<tr><th><label for="phone">電話</label></th>
<td><input type="tel" id="phone" name="phone" pattern="[0-9\-]{8,15}" placeholder="02-12345678"></td></tr>
<tr><td><button type="submit">送出</button></td></tr>
</table>
</form>
後端處理 (process.php) - 以 trim() 為核心的防禦性驗證
<?php
// 1. 統一清理輸入
$clean = [];
$fields = ['nickname', 'firstname', 'lastname', 'email', 'phone'];
foreach ($fields as $field) {
$clean[$field] = trim($_POST[$field] ?? '');
}
// 2. 驗證規則定義
$rules = [
'nickname' => ['required' => true, 'maxlen' => 20],
'firstname' => ['required' => true, 'maxlen' => 30],
'lastname' => ['required' => true, 'maxlen' => 30],
'email' => ['required' => true, 'maxlen' => 100, 'format' => 'email'],
'phone' => ['required' => false, 'format' => 'phone_tw'],
];
$errors = [];
// 3. 執行驗證
foreach ($rules as $field => $rule) {
$value = $clean[$field];
// 必填檢查 (trim 後為空字串視為未填)
if (!empty($rule['required']) && $value === '') {
$errors[$field] = "{$field} 為必填欄位";
continue;
}
// 長度檢查
if (isset($rule['maxlen']) && mb_strlen($value) > $rule['maxlen']) {
$errors[$field] = "{$field} 長度不得超過 {$rule['maxlen']} 字元";
}
// 格式檢查
if (!empty($value) && isset($rule['format'])) {
switch ($rule['format']) {
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field] = "Email 格式錯誤";
}
break;
case 'phone_tw':
// 台灣電話:02-12345678, 0912-345678, +886-2-12345678
if (!preg_match('/^(\+886|0)[0-9]{1,2}[-\s]?[0-9]{6,8}$/', $value)) {
$errors[$field] = "電話格式錯誤 (範例: 02-12345678)";
}
break;
}
}
}
// 4. 結果處理
if (!empty($errors)) {
// 重導回表單頁,攜帶錯誤訊息與舊值 (Session/Flash)
$_SESSION['form_errors'] = $errors;
$_SESSION['form_old'] = $clean;
header('Location: form.php');
exit;
}
// 5. 通過驗證,執行業務邏輯 (寫入 DB、發送 Email 等)
echo "資料驗證通過,準備處理...";
var_dump($clean);
?>
電話驗證函數獨立封裝 (可重用)
<?php
function validatePhone(string $number, string $type = 'tw'): bool {
$patterns = [
'tw' => '/^(\+886|0)[0-9]{1,2}[-\s]?[0-9]{6,8}$/', // 台灣
'cn' => '/^(\+86|0)?1[3-9]\d{9}$/', // 中國大陸手機
'us' => '/^(\+1|0)?[2-9]\d{2}[-\s]?[2-9]\d{2}[-\s]?\d{4}$/', // 美國
'generic' => '/^[\d\s\-\(\)\+]{7,20}$/', // 寬鬆通用
];
return preg_match($patterns[$type] ?? $patterns['generic'], $number) === 1;
}
// 使用
if (!validatePhone($clean['phone'], 'tw')) {
$errors['phone'] = '電話格式不正確';
}
?>
關鍵觀念:為什麼要 trim()?
- 使用者常不小心複製貼上含前後空白的字串。
- 資料庫唯一索引會將
'admin ' 與 'admin' 視為不同值。
strlen(' a ') = 3,但實質內容只有 1 字元。
- 原則: 所有字串輸入入口即清理,
trim() 是第一道防線。
現代框架驗證 (Laravel Validator 範例)
$validated = $request->validate([
'nickname' => 'required|string|max:20',
'email' => 'required|email|max:100|unique:users,email',
'phone' => 'nullable|regex:/^(\+886|0)[0-9]{1,2}[-\s]?[0-9]{6,8}$/',
]);
// 失敗自動重導並攜帶 errors 舊輸入