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步 - 无需在文本字段中输入任何内容直接点击“登录”按钮。 输出将如下面的图所示。