使用者未填寫欄位送出表單時,$_POST['field'] 為空字串 '',而非 null。若欄位為核取方塊且未勾選,則完全不存在於 $_POST 中。
<?php
// 處理留言表單
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 姓名:必填、非空白
$name = trim($_POST['name'] ?? '');
if ($name === '') {
$errors['name'] = '請輸入姓名';
}
// 內容:必填、最小長度
$comment = trim($_POST['comment'] ?? '');
if ($comment === '') {
$errors['comment'] = '請輸入留言內容';
} elseif (mb_strlen($comment) < 5) {
$errors['comment'] = '留言至少 5 個字元';
}
// 核取方塊:必須勾選
if (!isset($_POST['agree'])) {
$errors['agree'] = '請同意條款';
}
if (empty($errors)) {
// 儲存資料庫...
header('Location: success.php');
exit;
}
}
// 顯示表單與錯誤
?>
| 情況 | isset($v) | empty($v) | 說明 |
|---|---|---|---|
| 變數不存在 | false | true | empty 不報錯 |
$v = null | false | true | |
$v = '' | true | true | |
$v = 0 | true | true | empty 視 0 為空! |
$v = '0' | true | true | 字串 '0' 也視為空 |
$v = false | true | true | |
$v = [] | true | true |
<?php
function validateRequired(array $data, array $requiredFields): array {
$errors = [];
foreach ($requiredFields as $field => $label) {
// 1. 檢查是否存在(針對核取方塊/檔案上傳)
if (!array_key_exists($field, $data)) {
$errors[$field] = "$label 為必填";
continue;
}
$value = $data[$field];
// 2. 針對字串類型:trim 後不可為空
if (is_string($value)) {
$value = trim($value);
if ($value === '') {
$errors[$field] = "$label 不能為空";
}
}
// 3. 針對數值類型:允許 0,但不可為 null/空字串
elseif (is_numeric($value)) {
if ($value === '' || $value === null) {
$errors[$field] = "$label 不能為空";
}
}
// 4. 陣列(多選):至少一個元素
elseif (is_array($value)) {
if (empty($value)) {
$errors[$field] = "請至少選擇一項 $label";
}
}
}
return $errors;
}
// 使用
$errors = validateRequired($_POST, [
'name' => '姓名',
'email' => 'Email',
'age' => '年齡', // 允許 0
'agree' => '同意條款', // 核取方塊用 array_key_exists
'tags' => '標籤', // 多選陣列
]);
<!-- HTML5 內建驗證 -->
<script>
// JS 補強:自訂訊息、即時檢查
document.querySelector('form').addEventListener('submit', e => {
const form = e.target;
if (!form.checkValidity()) {
e.preventDefault();
form.reportValidity(); // 顯示瀏覽器內建提示
}
});
</script>
trim() === '' 最精確!is_numeric() || $val === '' 允許 0array_key_exists() 或 isset()empty($arr) 正確判斷是否有選項