Add multiple verification scenarios to your laravel verifier

Time:2021-1-24

preface

When we use the validator of the laravel framework, sometimes we need to verify the data of the form. Of course, laravel also provides us with
The validate method, formrequest and validator provided by the illuminate / HTTP / request object.

Formrequest creates a new file to separate our verification part to avoid controller bloated. If the authentication fails, a redirection response is generated to return the user to the previous location. These errors will also be flashed to the session so that they can be displayed on the page. If the incoming request is Ajax, the HTTP response of JSON data with 422 status code and verification error information will be returned to the user. If it is an interface request or Ajax, we may need to modify the returned JSON data to the format we want.

In our actual development, a module may need to have multiple verification scenarios. It is not too cumbersome to create a new formrequest for each verification scenario.
So it’s not convenient to add a verification scenario to laravel and adapt to different scenarios through a verification class, a module or multiple modules.

start

First, we encapsulate a base class BaseValidate.php And you can put it in APP / validate. Of course, you can also put it in other places, as long as you modify the namespace.

<?php
namespace App\Validate;

use Illuminate\Support\Facades\Validator;
/**
 *Extended verifier
 */
class BaseValidate {

  /**
   *Current validation rules
   * @var array
   */
  protected $rule = [];

  /**
   *Verification tips
   * @var array
   */
  protected $message = [];

  /**
   *Verify scenario definition
   * @var array
   */
  protected $scene = [];

  /**
   *Set the current verification scenario
   * @var array
   */
  protected $currentScene = null;

  /**
   *Validation failure error message
   * @var array
   */
  protected $error = [];

  /**
   *Rules for scenario validation
   * @var array
   */
  protected $only = [];


  /**
   *Set up verification scenarios
   * @access public
   *@ param string $name scene name
   * @return $this
   */
  public function scene($name)
  {
    //Set current scene
    $this->currentScene = $name;

    return $this;
  }

  /**
   *Data validation
   * @access public
   *@ param array $data
   *@ param mixed $rules validation rules
   *@ param array $message user defined verification information
   *@ param string $scene
   * @return bool
   */
  public function check($data, $rules = [], $message = [],$scene = '')
  {
    $this->error =[];
    if (empty($rules)) {
      //Read validation rules
      $rules = $this->rule;
    }
    if (empty($message)) {
      $message = $this->message;
    }

    //Read scene
    if (!$this->getScene($scene)) {
      return false;
    }

    //If the rules to be verified in the scene are not empty
    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);
    //Validation failed
    if ($validator->fails()) {
      $this->error = $validator->errors()->first();
      return false;
    }

    return !empty($this->error) ? false : true;
  }

  /**
   *Get the scenario of data validation
   * @access protected
   *@ param string $scene
   * @return void
   */
  protected function getScene($scene = '')
  {
    if (empty($scene)) {
      //Read the specified scene
      $scene = $this->currentScene;
    }
    $this->only = [];

    if (empty($scene)) {
      return true;
    }

    if (!isset($this->scene[$scene])) {
      //Write error not found for the specified scenario
      $this->error = "scene:".$scene.'is not found';
      return false;
    }
    //If the validation applicable scenario is set
    $scene = $this->scene[$scene];
    if (is_string($scene)) {
      $scene = explode(',', $scene);
    }
    //Fill in the fields that need to be verified in the scene into only
    $this->only = $scene;
    return true;
  }

  //Get error information
  public function getError()
  {
    return $this->error;
  } 
}

use

Next, let’s verify the submission information of an article. First, we create a new article verification class ArticleValidate.php And fill in some content

<?php
namespace App\Validate;

use App\Validate\BaseValidate;
/**
 *Article verifier
 */
class ArticleValidate extends BaseValidate {
  //Validation rules
  protected $rule =[
    'id'=>'required',
    'title' => 'required|max:255',
    'content' => 'required',
  ];
  //Custom validation information
  protected $message = [
    ' id.required '= >' missing article ID ',
    ' title.required '= >' please enter title ',
    ' title.max '= >' Title length cannot be greater than 255 ',
    ' content.required '= >' please input content ',
  ];

  //Custom Scene
  protected $scene = [
    'add'=>"title,content",
    'edit'=> ['id','title','content'],
  ];
}

As shown above, in this class, we define the validation rule, custom validation message, and validation scene

Non scene verification

We just need to define the rules

public function update(){

    $ArticleValidate = new ArticleValidate;

    $request_data = [
      'id'=>'1',
      'title '= >'I am the title of the article',
      'content' = > 'I am the content of the article',
    ];

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

There are four parameters in the check method, the first is the data to be verified, the second is the verification rule, the third is the user-defined error message, and the fourth is the verification scenario, in which 2, 3, and 4 are not required.
If the verification fails, we call the GETERROR () method to output the error information. GETERROR () does not support returning all the verification error information.

Scene verification

We need to define the verification scenario in the verification class in advance

As follows, string or array is supported. When string is used, the fields to be verified need to be separated

//Custom Scene
  protected $scene = [
    'add'=>"title,content",
    'edit'=> ['id','title','content'],
  ];

Then we do data validation in our controller

public function add(){

    $ArticleValidate = new ArticleValidate;

    $request_data = [
      'title '= >'I am the title of the article',
      'content' = > 'I am the content of the article',
    ];

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

  }

In controller verification

Of course, we also allow you not to create validation classes to validate data,

public function add(){

    $Validate = new BaseValidate;

    $request_data = [
      'title '= >'I am the title of the article',
      'content' = > 'I am the content of the article',
    ];

    $rule =[
      'id'=>'required',
      'title' => 'required|max:255',
      'content' => 'required',
    ];
    //Custom validation information
    $message = [
      ' id.required '= >' missing article ID ',
      ' title.required '= >' please enter title ',
      ' title.max '= >' Title length cannot be greater than 255 ',
      ' content.required '= >' please input content ',
    ];

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

Through the verification scenario, it not only reduces the bloated controller code, but also reduces too many formrequest files. Is it more convenient to customize JSON data,

Reference documents

Laravel form validation: form validation “laravel 5.5 Chinese document”
ThinkPHP verification scenario: https://www.kancloud.cn/manual/thinkphp5_ 1/354104

So far, this article about adding multiple verification scenarios to your laravel verifier is introduced here. For more information about laravel verifier, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!

This article is Yang PanYao’s original article. If you reprint it, you don’t need to contact me, but please indicate the source [Yang PanYao’s blog]: https://www.yangpanyao.com/archives/120.html

Recommended Today

JavaScript animation example: rotated equilateral triangle

Given that the coordinates of the center of gravity of an equilateral triangle are (x0, Y0) and the height is h, you can draw an equilateral triangle with horizontal bottom edge with the following statement.          ctx.beginPath();          ctx.moveTo(x0,y0-h*2/3);          ctx.lineTo(x0+h/Math.sqrt(3), y0+h/3);           ctx.lineTo(x0-h/Math.sqrt(3), y0+h/3);          ctx.lineTo(x0,y0-h*2/3);          ctx.closePath();          ctx.stroke(); Given the number of […]