laravel之验证器
开发中使用框架自带验证器进行参数验证
1.定义验证器基类,定义失败返回值
新建基础类文件 app > Http > Requests > BaseRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException; class BaseRequest extends FormRequest
{
protected function failedValidation(Validator $validator) {
$error= $validator->errors()->all();
throw new HttpResponseException(response()->json(['msg'=>'error','code'=>'500','data'=>$error[0]], 500));
}
}
?>
这里验证器继承BaseRequest.php
2.多场景验证
1)封装验证基类BaseValidate.php, 放置在app\Validate下, 其他地方也是OK的
<?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;
} }
2)使用 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: 验证场景
3) 非场景验证方式
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()暂不支持返回所有验证错误信息 。
4)控制器中使用
public function add(){ $ArticleValidate = new ArticleValidate; $request_data = [
'title'=>'我是文章的标题',
'content'=>'我是文章的内容',
]; if (!$ArticleValidate->scene('add')->check($request_data)) {
var_dump($ArticleValidate->getError());
} }
5)控制器内验证
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框架使用Illuminate/Validation验证器
1.关于Illuminate/Validation验证器 Validation 类用于验证数据以及获取错误消息. github地址:github.com/illuminate/validation 文 ...
- 9、 Struts2验证(声明式验证、自定义验证器)
1. 什么是Struts2 验证器 一个健壮的 web 应用程序必须确保用户输入是合法.有效的. Struts2 的输入验证 基于 XWork Validation Framework 的声明式验证: ...
- linux上使用google身份验证器(简版)
系统:centos6.6 下载google身份验证包google-authenticator-master(其实只是一个.zip文件,在windwos下解压,然后传进linux) #cd /data/ ...
- vue-validator(vue验证器)
官方文档:http://vuejs.github.io/vue-validator/zh-cn/index.html github项目地址:https://github.com/vuejs/vue-v ...
- 原生JS 表单提交验证器
转载:http://www.cnblogs.com/sicd/p/4613628.html 一.前言 最近在开发一个新项目,需要做登陆等一系列的表单提交页面.在经过“缜密”的讨论后,我们决定 不用外部 ...
- yii框架中验证器声明一组内置验证器可以使用短名称引用
1.内置验证器的短名称分别有: boolean: yii\validators\BooleanValidator captcha: yii\captcha\CaptchaValidator compa ...
- 通过Google身份验证器加强Linux帐户安全
下载Google的身份验证模块: # wget https://google-authenticator.googlecode.com/files/libpam-google-authenticato ...
- 谷歌身份验证器加强Linux帐户安全
下载 Google的身份验证模块 # wget https://google-authenticator.googlecode.com/files/libpam-google-authenticato ...
- JFinal极速开发实战-业务功能开发-通用表单验证器
提交表单数据时,需要经过前端的验证才能提交到后台,而后台的验证器再做一道数据的校验,成功之后才能进入action进行业务数据的处理. 在表单数据的验证中,数据类型的验证还是比较固定的.首先是对录入数据 ...
- yii 验证器和验证码
http://www.yiiframework.com/doc/api/1.1/CCaptcha http://www.cnblogs.com/analyzer/articles/1673015.ht ...
随机推荐
- 2024-09-04:用go语言,给定一个长度为n的数组 happiness,表示每个孩子的幸福值,以及一个正整数k,我们需要从这n个孩子中选出k个孩子。 在筛选过程中,每轮选择一个孩子时,所有尚未选
2024-09-04:用go语言,给定一个长度为n的数组 happiness,表示每个孩子的幸福值,以及一个正整数k,我们需要从这n个孩子中选出k个孩子. 在筛选过程中,每轮选择一个孩子时,所有尚未选 ...
- 小tips:HTML的实体
为了能在HTML文档中正确显示某些特殊字符,就需要使用HTML实体(entity).HTML实体就是对当前文档的编码方式不能包含的字符,提供一种转义表示. HTML实体定义 1.名称方式 名称方式会以 ...
- 合合信息推出国央企智能文档处理解决方案,AI赋能信创国产化
信息时代,数字化转型已成为推动经济高质量发展的关键力量.国央企是国民经济的重要支柱,其数字化转型进程关乎着自身与产业链上下游企业的共同发展.文档的智能化处理可有效提升信息流转的效率.促进知识的沉淀与传 ...
- DOM – MutationObserver
介绍 它和 IntersectionObserver, ResizeObserver 差不多, 都是观察 element 变化的. 它可以观察元素的 attribute 增加, 移除, 修改, app ...
- Git冲突解决技巧
在多人协作的软件开发项目中,Git 冲突是不可避免的现象.当两个或更多的开发者同时修改了同一段代码,并且尝试将这些修改合并到一起时,冲突就发生了.解决这些冲突是确保代码库健康和项目顺利进行的关键.以下 ...
- C#/.NET/.NET Core开发实战教程集
DotNetGuide介绍 DotNetGuide是一个专注于C#/.NET/.NET Core学习.工作.面试指南的GitHub知识库,该知识库在GitHub中Star数已突破6.5k+当然这离不开 ...
- `std::string_view`(c++17) 和 `std::stringstream` 使用区别·
std::string_view 和 std::stringstream 都是 C++ 中处理字符串的工具,但它们的设计目标和使用场景非常不同.我们可以通过几方面进行对比. 1. 设计目的和核心功能 ...
- 利用 ACME 实现SSL证书自动化配置更新
最近收到腾讯云的通知SSL证书要到期了,本想直接申请的发现现在申请的免费SSL证书有效期只有90天了,顺便了解了一下原因是包括Google在内的国际顶级科技公司一直都有在推进免费证书90天有效期的建议 ...
- 数据库周刊33丨腾讯Tbase新版本发布;“2020数据技术嘉年华”有奖话题遴选;阿里云技术面试题;APEX 实现数据库自动巡检;MYSQL OCP题库……
摘要:墨天轮数据库周刊第33期发布啦,每周1次推送本周数据库相关热门资讯.精选文章.干货文档. 热门资讯 1.中国移动国产OLTP数据库中标公告:南大金仓阿里,万里开源中兴 分获大单[摘要]近日,中国 ...
- 银河麒麟、中标麒麟学习实操资料汇总(含V4、V7、V10)
数据库和操作系统关系十分密切,因为数据库是运行于操作系统上的一个管理数据的应用.在数据库国产化替代的浪潮之下,一批批国产操作系统也崭露头角.墨天轮社区便选取了中国操作系统排行榜上排名靠前的麒麟软件,依 ...