控制器驗證
如果你需要在控制器中進行驗證,并且繼承了\think\Controller的話,可以調用控制器類提供的validate方法進行驗證,如下:
$result = $this->validate(
[
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com',
],
[
'name' => 'require|max:25',
'email' => 'email',
]);
if(true !== $result){
// 驗證失敗 輸出錯誤信息(xi)
dump($result);
}
如果定義了(le)驗證器類的話(hua),例如:
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name' => 'require|max:25',
'email' => 'email',
];
protected $message = [
'name.require' => '用戶名必須',
'email' => '郵(you)箱格式錯誤',
];
protected $scene = [
'add' => ['name','email'],
'edit' => ['email'],
];
}
控(kong)制器中的驗證(zheng)代碼可以簡化為(wei):
$result = $this->validate($data,'User');
if(true !== $result){
// 驗證(zheng)失敗 輸出錯誤信(xin)息(xi)
dump($result);
}
如(ru)果要使(shi)用場景,可以使(shi)用:
$result = $this->validate($data,'User.edit');
if(true !== $result){
// 驗證失(shi)敗 輸(shu)出(chu)錯誤信(xin)息(xi)
dump($result);
}
在validate方(fang)法中還支持做一(yi)些前(qian)置的操作回調,使用方(fang)式(shi)如下(xia):
$result = $this->validate($data,'User.edit',[],[$this,'some']);
if(true !== $result){
// 驗(yan)證(zheng)失敗 輸出(chu)錯(cuo)誤信息
dump($result);
}
文檔最后更新時間:2018-04-26 10:47:01
未解決你的問題?請到「問答社區」反饋你遇到的問題
