前言
在我们使用 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;
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
