Laravel 提供功能強大的驗證系統,支援豐富內建規則、靈活的錯誤訊息管理、自定義規則擴展,本文系統整理核心用法與進階技巧。
$validator = Validator::make(
['name' => 'Dayle'], // 待驗證資料
['name' => 'required|min:5'] // 規則:管道符或陣列皆可
);
if ($validator->fails()) {
$messages = $validator->messages(); // MessageBag 實例
$failedRules = $validator->failed(); // 未通過規則陣列
}
// 取得單一欄位第一個錯誤
echo $messages->first('email');
// 遍歷單一欄位所有錯誤
foreach ($messages->get('email') as $msg) { /* ... */ }
// 遍歷所有錯誤
foreach ($messages->all() as $msg) { /* ... */ }
// 檢查欄位是否有錯誤
if ($messages->has('email')) { /* ... */ }
// 自訂格式輸出
echo $messages->first('email', ':message
');
foreach ($messages->all('重導向時使用 withErrors($validator),Laravel 會自動將錯誤存入 Session,下一請求視圖中直接使用 $errors 變數(MessageBag 實例):
// 路由
Route::post('register', function() {
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('register')->withErrors($validator);
}
});
// 視圖
{{ $errors->first('email') }}
| 規則 | 說明 |
|---|---|
| accepted | 值為 yes/on/1,適合服務條款勾選 |
| active_url | 有效 URL(checkdnsrr) |
| after:date / before:date | 日期比較(strtotime 解析) |
| alpha / alpha_dash / alpha_num | 字母/字母數字底線中劃線 |
| between:min,max | 範圍驗證(字串/數字/檔案大小) |
| confirmed | 需配對 欄位_confirmation |
| date / date_format:format | 日期格式驗證 |
| different:field | 與指定欄位不同 |
| 電子郵件格式 | |
| exists:table,column | 資料庫存在性檢查 |
| image | 圖片檔 |
| in:foo,bar / not_in:foo,bar | 白/黑名單 |
| integer / numeric | 整數/數字 |
| ip | IP 位址 |
| max:value / min:value | 最大/最小值 |
| mimes:jpeg,png | 檔案 MIME 類型 |
| regex:pattern | 正則表達式(需用陣列語法) |
| required / required_if / required_with | 條件必填 |
| same:field | 與指定欄位相同 |
| size:value | 大小完全相等 |
| unique:table,column,except,idColumn | 資料庫唯一性 |
| url | URL 格式 |
// 1. 直接傳遞 $messages = ['required' => ':attribute 欄位為必填']; $validator = Validator::make($input, $rules, $messages); // 2. 指定欄位.規則 $messages = ['email.required' => '請輸入信箱!']; // 3. 語言檔 // app/lang/zh-TW/validation.php 'custom' => ['email' => ['required' => '請輸入信箱!']]
Validator::extend('foo', function($attribute, $value, $parameters) {
return $value == 'foo';
});
Validator::extend('foo', 'FooValidator@validate');
class CustomValidator extends Illuminate\Validation\Validator {
public function validateFoo($attribute, $value, $parameters) {
return $value == 'foo';
}
// 自定義佔位符替換
protected function replaceFoo($message, $attribute, $rule, $parameters) {
return str_replace(':foo', $parameters[0], $message);
}
}
// 註冊解析器
Validator::resolver(function($translator, $data, $rules, $messages) {
return new CustomValidator($translator, $data, $rules, $messages);
});
檔案驗證同樣支援 size、mimes 等規則,傳遞方式與一般欄位相同。
善用驗證系統能大幅提升應用健壯性,建議將常用規則封裝為 Form Request 類別集中管理。