表單提交前後端都需驗證必填欄位。PHP 端核心在於 trim() 去除空白後判斷是否為空,本文對比多種判斷方式,並給出生產級驗證類別。
| 代碼 | 結果 | 說明 |
|---|---|---|
!$_POST['name'] | 空字串、0、"0"、null、false 皆為真 | 過於寬鬆,"0" 會被視為空 |
empty($_POST['name']) | 同上 | 同上,不會觸發 undefined notice |
trim($_POST['name']) === '' | 僅空字串或純空白為真 | 推薦,精確判斷「用戶未輸入內容」 |
strlen(trim($_POST['name'])) === 0 | 同上 | 等同上一行 |
mb_strlen(trim($_POST['name']), 'UTF-8') === 0 | 同上 (多位元組安全) | 含中文時更準確 |
<?php
// ErrorCheck.php
$errors = [];
$fields = ['nickname' => '暱稱', 'title' => '標題'];
foreach ($fields as $field => $label) {
$value = trim($_POST[$field] ?? '');
if ($value === '') {
$errors[] = "$label 為必填欄位";
}
}
if ($errors) {
echo '<div class="errors"><ul><li>' . implode('</li><li>', $errors) . '</li></ul></div>';
echo '<a href="javascript:history.back()">返回修正</a>';
exit;
}
// 通過驗證,處理業務邏輯...
echo '提交成功!';
?>
<?php
class Validator {
private $data;
private $errors = [];
private $rules = [];
public function __construct(array $data) {
$this->data = $data;
}
public function rule(string $field, string $label, array $rules) {
$this->rules[$field] = ['label' => $label, 'rules' => $rules];
return $this;
}
public function validate(): bool {
foreach ($this->rules as $field => $config) {
$value = $this->data[$field] ?? null;
$label = $config['label'];
foreach ($config['rules'] as $rule) {
$params = [];
if (preg_match('/(\w+)\((.*)\)/', $rule, $m)) {
$rule = $m[1];
$params = array_map('trim', explode(',', $m[2]));
}
$method = 'check' . ucfirst($rule);
if (method_exists($this, $method)) {
if (!$this->$method($value, $label, ...$params)) {
// 驗證失敗,錯誤訊息已在方法中加入
break; // 同一欄位首個失敗即停止
}
}
}
}
return empty($this->errors);
}
public function getErrors(): array { return $this->errors; }
// 內建規則
protected function checkRequired($value, $label) {
if (!isset($value) || trim((string)$value) === '') {
$this->errors[] = "$label 不能為空";
return false;
}
return true;
}
protected function checkMinLen($value, $label, $len) {
if (mb_strlen(trim($value), 'UTF-8') < (int)$len) {
$this->errors[] = "$label 至少需要 $len 個字符";
return false;
}
return true;
}
protected function checkMaxLen($value, $label, $len) {
if (mb_strlen(trim($value), 'UTF-8') > (int)$len) {
$this->errors[] = "$label 不得超過 $len 個字符";
return false;
}
return true;
}
protected function checkEmail($value, $label) {
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->errors[] = "$label 格式不正確";
return false;
}
return true;
}
protected function checkRegex($value, $label, $pattern) {
if (!preg_match($pattern, $value)) {
$this->errors[] = "$label 格式不符合要求";
return false;
}
return true;
}
}
// 使用範例
$v = new Validator($_POST);
$v->rule('nickname', '暱稱', ['required', 'minLen(2)', 'maxLen(20)'])
->rule('email', '電子郵件', ['required', 'email'])
->rule('phone', '手機', ['required', 'regex(/^1[3-9]\d{9}$/)']);
if (!$v->validate()) {
foreach ($v->getErrors() as $err) echo "$err<br/>";
exit;
}
// 繼續業務邏輯...
?>
<form method="post" action="submit.php">
<input type="text" name="nickname" required minlength="2" maxlength="20"
placeholder="請輸入暱稱">
<input type="email" name="email" required placeholder="email@example.com">
<input type="tel" name="phone" required pattern="1[3-9]\d{9}"
placeholder="13800138000" title="請輸入有效手機號">
<button type="submit">提交</button>
</form>
原則:前端驗證提升體驗,後端驗證保障安全,兩者缺一不可。