表單/接口參數驗證是Web應用核心邏輯。本文設計一個可擴展的Validation類,內建常用正則規則庫,支持鏈式調用、批量驗證、錯誤信息收集、自定義規則,並兼容PSR-12編碼規範。
<?php
namespace App\Validation;
class Validation {
// 內建正則規則庫
private static array $patterns = [
'letter_number' => '/^[0-9A-Za-z]+$/',
'account' => '/^[0-9A-Za-z_]+$/',
'ids' => '/^[0-9]+(,[0-9]+)*$/',
'number' => '/^[0-9]+$/',
'id_card' => '/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/',
'email' => '/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/',
'mobile_cn' => '/^1[3-9]\d{9}$/',
'url' => '/^https?:\/\/[^\s]+$/',
'ipv4' => '/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d)$/',
'date' => '/^\d{4}-\d{2}-\d{2}$/', // 格式校驗,邏輯有效性需date()驗證
];
// 驗證結果收集
private array $errors = [];
// 鏈式調用:添加字段規則
public function field(string $name, mixed $value, array $rules): self {
foreach ($rules as $rule) {
if (is_string($rule)) $rule = ['type' => $rule];
$this->applyRule($name, $value, $rule);
}
return $this;
}
private function applyRule(string $name, mixed $value, array $rule): void {
$type = $rule['type'];
$msg = $rule['message'] ?? "$name 驗證失敗 ($type)";
$pass = true;
switch ($type) {
case 'required':
$pass = $value !== null && $value !== '' && $value !== [];
break;
case 'regex':
$pattern = $rule['pattern'] ?? (self::$patterns[$rule['pattern']] ?? null);
if (!$pattern) throw new \InvalidArgumentException("未知正則規則: {$rule['pattern']}");
$pass = (bool)preg_match($pattern, (string)$value);
break;
case 'min_length':
$pass = mb_strlen((string)$value) >= ($rule['length'] ?? 0);
break;
case 'max_length':
$pass = mb_strlen((string)$value) <= ($rule['length'] ?? PHP_INT_MAX);
break;
case 'between':
$len = mb_strlen((string)$value);
$pass = $len >= ($rule['min'] ?? 0) && $len <= ($rule['max'] ?? PHP_INT_MAX);
break;
case 'in':
$pass = in_array($value, $rule['values'] ?? [], true);
break;
case 'custom':
$pass = ($rule['callable'] ?? fn() => false)($value);
break;
}
if (!$pass) $this->errors[$name][] = $msg;
}
// 批量驗證數組
public function validate(array $data, array $rulesMap): self {
foreach ($rulesMap as $field => $rules) {
$value = $data[$field] ?? null;
$this->field($field, $value, (array)$rules);
}
return $this;
}
public function hasErrors(): bool { return !empty($this->errors); }
public function getErrors(): array { return $this->errors; }
public function firstError(): ?string { return $this->errors ? reset($this->errors)[0] : null; }
public function getErrorMessages(): array { return array_map(fn($msgs) => implode('; ', $msgs), $this->errors); }
// 靜態快捷方法
public static function make(array $data, array $rules): self {
return (new self())->validate($data, $rules);
}
}
use App\Validation\Validation;
$data = $_POST; // 或 API JSON 輸入
$rules = [
'username' => ['required', ['type' => 'regex', 'pattern' => 'account'], ['type' => 'max_length', 'length' => 20]],
'email' => ['required', ['type' => 'regex', 'pattern' => 'email']],
'password' => ['required', ['type' => 'min_length', 'length' => 8], ['type' => 'regex', 'pattern' => '/(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+/']],
'age' => ['required', ['type' => 'regex', 'pattern' => 'number'], ['type' => 'between', 'min' => 1, 'max' => 120]],
'role' => ['required', ['type' => 'in', 'values' => ['admin', 'editor', 'viewer']]],
];
$validator = Validation::make($data, $rules);
if ($validator->hasErrors()) {
// API返回
return response()->json(['code' => 422, 'errors' => $validator->getErrorMessages()], 422);
// 或視圖渲染
// foreach ($validator->getErrors() as $field => $msgs) { ... }
}
// 驗證通過,處理業務邏輯
Validation::$patterns['my_rule'] = '/pattern/';Validation重寫applyRule或添加case 'my_type':。Validator::make($data, $rules)->validate()功能更強(異步、條件驗證、After鉤子)。static $compiled = []; $compiled[$pattern] ??= $pattern;避免重複編譯(PHP 8.1+ JIT自動優化)。if ($this->errors && $stopOnFirstFailure) return $this;。封裝通用驗證類,統一項目驗證風格,減少重複代碼,提升安全性與可維護性。