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