欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

為你的 Laravel 驗證器加上多驗證場景的實現(xiàn)

 更新時間:2020年04月07日 15:30:16   作者:割了動脈喝脈動  
這篇文章主要介紹了為你的 Laravel 驗證器加上多驗證場景的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

在我們使用 laravel 框架的驗證器,有的時候需要對表單等進行數(shù)據(jù)驗證,當(dāng)然 laravel 也為我們提供了
Illuminate\Http\Request 對象提供的 validate 方法 以及 FormRequest 和 Validator。

FormRequest 通過新建文件將我們的驗證部分單獨分開,來避免控制器臃腫。如果驗證失敗,就會生成一個讓用戶返回到先前的位置的重定向響應(yīng)。這些錯誤也會被閃存到 Session 中,以便這些錯誤都可以在頁面中顯示出來。如果傳入的請求是 AJAX,會向用戶返回具有 422 狀態(tài)代碼和驗證錯誤信息的 JSON 數(shù)據(jù)的 HTTP 響應(yīng)。如果是接口請求或 ajax, 那么我們可能還需要將返回的 json 數(shù)據(jù)修改成我們想要的格式。

當(dāng)我們實際開發(fā)中,可能一個模塊需要有多個驗證場景,如果為每一個驗證場景都新建一個 FormRequest 不就太過繁瑣了。
那么給 laravel 加上一個驗證場景通過一個驗證類一個模塊或多個模塊來適應(yīng)不同的場景不就方便很多了。

開始

首先 我們封裝了一個基類 BaseValidate.php 并將其放在 app\Validate 下,當(dāng)然你也可以放在其他地方,只要修改好命名空間就好。

<?php
namespace App\Validate;

use Illuminate\Support\Facades\Validator;
/**
 * 擴展驗證器
 */
class BaseValidate {

  /**
   * 當(dāng)前驗證規(guī)則
   * @var array
   */
  protected $rule = [];

  /**
   * 驗證提示信息
   * @var array
   */
  protected $message = [];

  /**
   * 驗證場景定義
   * @var array
   */
  protected $scene = [];

  /**
   * 設(shè)置當(dāng)前驗證場景
   * @var array
   */
  protected $currentScene = null;

  /**
   * 驗證失敗錯誤信息
   * @var array
   */
  protected $error = [];

  /**
   * 場景需要驗證的規(guī)則
   * @var array
   */
  protected $only = [];


  /**
   * 設(shè)置驗證場景
   * @access public
   * @param string $name 場景名
   * @return $this
   */
  public function scene($name)
  {
    // 設(shè)置當(dāng)前場景
    $this->currentScene = $name;

    return $this;
  }

  /**
   * 數(shù)據(jù)驗證
   * @access public
   * @param array   $data 數(shù)據(jù)
   * @param mixed   $rules 驗證規(guī)則
   * @param array  $message 自定義驗證信息
   * @param string  $scene 驗證場景
   * @return bool
   */
  public function check($data, $rules = [], $message = [],$scene = '')
  {
    $this->error =[];
    if (empty($rules)) {
      //讀取驗證規(guī)則
      $rules = $this->rule;
    }
    if (empty($message)) {
      $message = $this->message;
    }

    //讀取場景
    if (!$this->getScene($scene)) {
      return false;
    }

    //如果場景需要驗證的規(guī)則不為空
    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;
  }

  /**
   * 獲取數(shù)據(jù)驗證的場景
   * @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;
    }
    // 如果設(shè)置了驗證適用場景
    $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 并填充一些內(nèi)容

<?php
namespace App\Validate;

use App\Validate\BaseValidate;
/**
 * 文章驗證器
 */
class ArticleValidate extends BaseValidate {
  //驗證規(guī)則
  protected $rule =[
    'id'=>'required',
    'title' => 'required|max:255',
    'content' => 'required',
  ];
  //自定義驗證信息
  protected $message = [
    'id.required'=>'缺少文章id',
    'title.required'=>'請輸入title',
    'title.max'=>'title長度不能大于 255',
    'content.required'=>'請輸入內(nèi)容',
  ];

  //自定義場景
  protected $scene = [
    'add'=>"title,content",
    'edit'=> ['id','title','content'],
  ];
}

如上所示,在這個類中我們定義了驗證規(guī)則 rule,自定義驗證信息 message,以及驗證場景 scene

非場景驗證

我們只需要定義好規(guī)則

public function update(){

    $ArticleValidate = new ArticleValidate;

    $request_data = [
      'id'=>'1',
      'title'=>'我是文章的標(biāo)題',
      'content'=>'我是文章的內(nèi)容',
    ];

    if (!$ArticleValidate->check($request_data)) {
      var_dump($ArticleValidate->getError());
    }
  }

check 方法中總共有四個參數(shù),第一個要驗證的數(shù)據(jù),第二個驗證規(guī)則,第三個自定義錯誤信息,第四個驗證場景,其中 2,3,4 非必傳。
如果驗證未通過我們調(diào)用 getError() 方法來輸出錯誤信息,getError()暫不支持返回所有驗證錯誤信息 。

場景驗證

我們需要提前在驗證類中定義好驗證場景

如下,支持使用字符串或數(shù)組,使用字符串時,要驗證的字段需用 , 隔開

//自定義場景
  protected $scene = [
    'add'=>"title,content",
    'edit'=> ['id','title','content'],
  ];

然后在我們的控制器進行數(shù)據(jù)驗證

public function add(){

    $ArticleValidate = new ArticleValidate;

    $request_data = [
      'title'=>'我是文章的標(biāo)題',
      'content'=>'我是文章的內(nèi)容',
    ];

    if (!$ArticleValidate->scene('add')->check($request_data)) {
      var_dump($ArticleValidate->getError());
    }

  }

控制器內(nèi)驗證

當(dāng)然我們也允許你不創(chuàng)建驗證類來驗證數(shù)據(jù),

public function add(){

    $Validate = new BaseValidate;

    $request_data = [
      'title'=>'我是文章的標(biāo)題',
      'content'=>'我是文章的內(nèi)容',
    ];

    $rule =[
      'id'=>'required',
      'title' => 'required|max:255',
      'content' => 'required',
    ];
    //自定義驗證信息
    $message = [
      'id.required'=>'缺少文章id',
      'title.required'=>'請輸入title',
      'title.max'=>'title長度不能大于 255',
      'content.required'=>'請輸入內(nèi)容',
    ];

    if (!$Validate->check($request_data,$rule,$message)) {
      var_dump($Validate->getError());
    }
  }

通過驗證場景,既減少了控制器代碼的臃腫,又減少了 FormRequest 文件過多,還可以自定義 json 數(shù)據(jù)是不是方便多了呢,

參考文檔

laravel 表單驗證 :表單驗證《Laravel 5.5 中文文檔》
thinkphp 驗證場景 :https://www.kancloud.cn/manual/thinkphp5_1/354104

到此這篇關(guān)于為你的 Laravel 驗證器加上多驗證場景的實現(xiàn)的文章就介紹到這了,更多相關(guān)Laravel 驗證器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

本文為楊攀遙原創(chuàng)文章,如若轉(zhuǎn)載,無需和我聯(lián)系,但請注明出處 [楊攀遙的博客]:https://www.yangpanyao.com/archives/120.html

相關(guān)文章

最新評論