Laravel可用的驗證規則
|
||
---|---|---|
Accepted | Active URL | After (Date) |
Alpha | Alpha Dash | Alpha Numeric |
Array | Before (Date) | Between |
Boolean | Confirmed | Date |
Date Format | Different | Digits |
Digits Between | Exists (Database) | |
Image (File) | In | Integer |
IP Address | JSON | Max |
MIME Types(File) | Min | Not In |
Numeric | Regular Expression | Required |
Required If | Required Unless | Required With |
Required With All | Required Without | Required Without All |
Same | Size | String |
Timezone | Unique (Database) | URL |
Laravel總是會檢查是否存在錯誤在對談資料中,如果它們都可用就會自動將其系結到檢視。 因此,要注意,$error 變數總是會在每次請求檢視時都是可以存取的,$errors 變數就類似在應用中是始終定義的,可以放心使用。$errors 變數是 Illuminate\Support\MessageBag的一個範例。可以通過將程式碼將錯誤訊息顯示在檢視檔案中,如下所示。
@if (count($errors) > 0) <div class = "alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
php artisan make:controller ValidationController
第3步 - 複製下面的程式碼到檔案- app/Http/Controllers/ValidationController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ValidationController extends Controller { public function showform(){ return view('login'); } public function validateform(Request $request){ print_r($request->all()); $this->validate($request,[ 'username'=>'required|max:8', 'password'=>'required' ]); } }
resources/views/login.blade.php
<html> <head> <title>登入範例表單</title> </head> <body> @if (count($errors) > 0) <div class = "alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <?php echo Form::open(array('url'=>'/validation')); ?> <table border = '1'> <tr> <td align = 'center' colspan = '2'>登入範例</td> </tr> <tr> <td>使用者名:</td> <td><?php echo Form::text('username'); ?></td> </tr> <tr> <td>密碼:</td> <td><?php echo Form::password('password'); ?></td> </tr> <tr> <td align = 'center' colspan = '2'> <?php echo Form::submit('登陸'); ? ></td> </tr> </table> <?php echo Form::close(); ?> </body> </html>
第5步 - 新增以下行到 app/Http/routes.php.
app/Http/routes.php
Route::get('/validation','ValidationController@showform'); Route::post('/validation','ValidationController@validateform');
http://localhost:8000/validation
第7步 - 無需在文字欄位中輸入任何內容直接點選「登入」按鈕。 輸出將如下面的圖所示。