前言
在我們使用 laravel 框架的驗證器,有的時候需要對表單等進行數據驗證,當然 laravel 也為我們提供了
Illuminate\Http\Request 對象提供的 validate 方法 以及 FormRequest 和 Validator。
FormRequest 通過新建文件將我們的驗證部分單獨分開,來避免控制器臃腫。如果驗證失敗,就會生成一個讓用戶返回到先前的位置的重定向響應。這些錯誤也會被閃存到 Session 中,以便這些錯誤都可以在頁面中顯示出來。如果傳入的請求是 AJAX,會向用戶返回具有 422 狀態代碼和驗證錯誤信息的 JSON 數據的 HTTP 響應。如果是接口請求或 ajax, 那么我們可能還需要將返回的 json 數據修改成我們想要的格式。
當我們實際開發中,可能一個模塊需要有多個驗證場景,如果為每一個驗證場景都新建一個 FormRequest 不就太過繁瑣了。
那么給 laravel 加上一個驗證場景通過一個驗證類一個模塊或多個模塊來適應不同的場景不就方便很多了。
開始
首先 我們封裝了一個基類 BaseValidate.php 并將其放在 app\Validate 下,當然你也可以放在其他地方,只要修改好命名空間就好。
?php
namespace App\Validate;
use Illuminate\Support\Facades\Validator;
/**
* 擴展驗證器
*/
class BaseValidate {
/**
* 當前驗證規則
* @var array
*/
protected $rule = [];
/**
* 驗證提示信息
* @var array
*/
protected $message = [];
/**
* 驗證場景定義
* @var array
*/
protected $scene = [];
/**
* 設置當前驗證場景
* @var array
*/
protected $currentScene = null;
/**
* 驗證失敗錯誤信息
* @var array
*/
protected $error = [];
/**
* 場景需要驗證的規則
* @var array
*/
protected $only = [];
/**
* 設置驗證場景
* @access public
* @param string $name 場景名
* @return $this
*/
public function scene($name)
{
// 設置當前場景
$this->currentScene = $name;
return $this;
}
/**
* 數據驗證
* @access public
* @param array $data 數據
* @param mixed $rules 驗證規則
* @param array $message 自定義驗證信息
* @param string $scene 驗證場景
* @return bool
*/
public function check($data, $rules = [], $message = [],$scene = '')
{
$this->error =[];
if (empty($rules)) {
//讀取驗證規則
$rules = $this->rule;
}
if (empty($message)) {
$message = $this->message;
}
//讀取場景
if (!$this->getScene($scene)) {
return false;
}
//如果場景需要驗證的規則不為空
if (!empty($this->only)) {
$new_rules = [];
foreach ($this->only as $key => $value) {
if (array_key_exists($value,$rules)) {
$new_rules[$value] = $rules[$value];
}
}
$rules = $new_rules;
}
// var_dump($rules);die;
$validator = Validator::make($data,$rules,$message);
//驗證失敗
if ($validator->fails()) {
$this->error = $validator->errors()->first();
return false;
}
return !empty($this->error) ? false : true;
}
/**
* 獲取數據驗證的場景
* @access protected
* @param string $scene 驗證場景
* @return void
*/
protected function getScene($scene = '')
{
if (empty($scene)) {
// 讀取指定場景
$scene = $this->currentScene;
}
$this->only = [];
if (empty($scene)) {
return true;
}
if (!isset($this->scene[$scene])) {
//指定場景未找到寫入error
$this->error = "scene:".$scene.'is not found';
return false;
}
// 如果設置了驗證適用場景
$scene = $this->scene[$scene];
if (is_string($scene)) {
$scene = explode(',', $scene);
}
//將場景需要驗證的字段填充入only
$this->only = $scene;
return true;
}
// 獲取錯誤信息
public function getError()
{
return $this->error;
}
}
使用
接下來我們來驗證一個文章的提交信息,首先我們新建一個文章驗證類 ArticleValidate.php 并填充一些內容
?php
namespace App\Validate;
use App\Validate\BaseValidate;
/**
* 文章驗證器
*/
class ArticleValidate extends BaseValidate {
//驗證規則
protected $rule =[
'id'=>'required',
'title' => 'required|max:255',
'content' => 'required',
];
//自定義驗證信息
protected $message = [
'id.required'=>'缺少文章id',
'title.required'=>'請輸入title',
'title.max'=>'title長度不能大于 255',
'content.required'=>'請輸入內容',
];
//自定義場景
protected $scene = [
'add'=>"title,content",
'edit'=> ['id','title','content'],
];
}
如上所示,在這個類中我們定義了驗證規則 rule,自定義驗證信息 message,以及驗證場景 scene
非場景驗證
我們只需要定義好規則
public function update(){
$ArticleValidate = new ArticleValidate;
$request_data = [
'id'=>'1',
'title'=>'我是文章的標題',
'content'=>'我是文章的內容',
];
if (!$ArticleValidate->check($request_data)) {
var_dump($ArticleValidate->getError());
}
}
check 方法中總共有四個參數,第一個要驗證的數據,第二個驗證規則,第三個自定義錯誤信息,第四個驗證場景,其中 2,3,4 非必傳。
如果驗證未通過我們調用 getError() 方法來輸出錯誤信息,getError()暫不支持返回所有驗證錯誤信息 。
場景驗證
我們需要提前在驗證類中定義好驗證場景
如下,支持使用字符串或數組,使用字符串時,要驗證的字段需用 , 隔開
//自定義場景
protected $scene = [
'add'=>"title,content",
'edit'=> ['id','title','content'],
];
然后在我們的控制器進行數據驗證
public function add(){
$ArticleValidate = new ArticleValidate;
$request_data = [
'title'=>'我是文章的標題',
'content'=>'我是文章的內容',
];
if (!$ArticleValidate->scene('add')->check($request_data)) {
var_dump($ArticleValidate->getError());
}
}
控制器內驗證
當然我們也允許你不創建驗證類來驗證數據,
public function add(){
$Validate = new BaseValidate;
$request_data = [
'title'=>'我是文章的標題',
'content'=>'我是文章的內容',
];
$rule =[
'id'=>'required',
'title' => 'required|max:255',
'content' => 'required',
];
//自定義驗證信息
$message = [
'id.required'=>'缺少文章id',
'title.required'=>'請輸入title',
'title.max'=>'title長度不能大于 255',
'content.required'=>'請輸入內容',
];
if (!$Validate->check($request_data,$rule,$message)) {
var_dump($Validate->getError());
}
}
通過驗證場景,既減少了控制器代碼的臃腫,又減少了 FormRequest 文件過多,還可以自定義 json 數據是不是方便多了呢,
參考文檔
laravel 表單驗證 :表單驗證《Laravel 5.5 中文文檔》
thinkphp 驗證場景 :https://www.kancloud.cn/manual/thinkphp5_1/354104
到此這篇關于為你的 Laravel 驗證器加上多驗證場景的實現的文章就介紹到這了,更多相關Laravel 驗證器內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
本文為楊攀遙原創文章,如若轉載,無需和我聯系,但請注明出處 [楊攀遙的博客]:https://www.yangpanyao.com/archives/120.html
您可能感興趣的文章:- Laravel框架表單驗證詳解
- Laravel 5框架學習之表單驗證
- 使用 laravel sms 構建短信驗證碼發送校驗功能
- Laravel中unique和exists驗證規則的優化詳解
- Laravel框架用戶登陸身份驗證實現方法詳解
- Laravel 5.5 的自定義驗證對象/類示例代碼詳解
- laravel中短信發送驗證碼的實現方法
- laravel5.4生成驗證碼的實例講解
- laravel5.4生成驗證碼的代碼