控制器驗證
如果你需要在控制器中進行驗證,并且繼承了\think\Controller
的話,可以調用控制器類提供的validate
方法進行驗證,如下:
$result = $this->validate(
[
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com',
],
[
'name' => 'require|max:25',
'email' => 'email',
]);
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
如果定義了驗證器類的話,例如:
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'],
];
}
控制器中的驗證代碼可以簡化為:
$result = $this->validate($data,'User');
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
如果要使用場景,可以使用:
$result = $this->validate($data,'User.edit');
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
在validate方法中還支持做一些前置的操作回調,使用方式如下:
$result = $this->validate($data,'User.edit',[],[$this,'some']);
if(true !== $result){
// 驗證失敗 輸出錯誤信息
dump($result);
}
文檔最后更新時間:2018-04-26 10:47:01
未解決你的問題?請到「問答社區」反饋你遇到的問題