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