系統的控制器基類還提供了數據驗證功能,可以調用`validate方法`進行數據驗證,如下:
~~~
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function hello()
{
$result = $this->validate(
[
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com',
],
[
'name' => 'require|max:25',
'email' => 'email',
]);
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
}
}
~~~
如果你有一些規范的規則需要定義,可以定義一個相關的驗證器類。
例如,下面給用戶相關的驗證定義了一個驗證器類:
~~~
<?php
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name' => 'require|max:25',
'email' => 'email',
];
protected $message = [
'name.require' => '用戶名必須',
'email' => '郵箱格式錯誤',
];
protected $scene = [
'add' => ['name','email'],
'edit' => ['email'],
];
}
~~~
控制器中的驗證代碼可以簡化為:
~~~
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function hello()
{
$result = $this->validate($data,'User');
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
}
}
~~~
如果對數據驗證使用場景,可以使用:
~~~
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function hello()
{
$result = $this->validate($data,'User.edit');
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
}
}
~~~
更多的驗證用法在表單請求和驗證一講中會更詳細的描述。
#### 總結
了解完了系統的基礎控制器的相關功能后,下一講我們就來了解下請求對象的概念及用法。