如何优雅的使用 laravel 的 validator验证方法


Posted in PHP onNovember 11, 2018

web 开发过程中经常会需要进行参数验证,laravel 中我们常用 validator 或者 request 这两种方法来进行验证,但是这两种验证都不是很方便进行自定义提示信息,自定义验证规则,所以下面来介绍一种很方便的用法:

新建抽象类

<?php

namespace App\Http\Validators;

use Validator;

abstract class AbstractValidator
{

 /**
  * Validator
  *
  * @var \Illuminate\Validation\Factory
  */
 protected $validator;

 /**
  * Validation data key => value array
  *
  * @var array
  */
 protected $data = array();

 /**
  * Validation errors
  *
  * @var array
  */
 protected $errors = array();

 /**
  * Validation rules
  *
  * @var array
  */
 protected $rules = array();

 /**
  * Validation messages
  *
  * @var array
  */
 protected $messages = array();

 /**
  * Validation codes
  *
  * @var array
  */
 protected $codes = array();

 public function __construct(array $data)
 {
  $this->data = $data;
  $this->before();
  $this->validator = Validator::make($this->data, $this->rules, $this->messages);
  $this->after();
 }

 /**
  * Set data to validate
  *
  * @return validator
  */
 public function getValidator()
 {
  return $this->validator;
 }

 /**
  * Set data to validate
  *
  * @return $this
  */
 public function with(array $data)
 {
  $this->data = $data;
  $this->before();
  $this->validator = $this->validator->make($this->data, $this->rules, $this->messages);
  $this->after();
  return $this;
 }

 /**
  * Validation passes or fails
  *
  * @return boolean
  */
 public function passes()
 {
  if ($this->validator->fails()) {
   $this->errors = $this->validator->messages();

   return false;
  }

  return true;
 }

 /**
  * Return errors, if any
  *
  * @return array
  */
 public function errors()
 {
  return $this->errors;
 }

 /**
  * Return errors codes, if any
  *
  * @return array
  */
 public function getCodes()
 {
  return $this->codes;
 }

 /**
  * getRules
  *
  * @return array
  */
 public function getRules()
 {
  return $this->rules;
 }

 /**
  * getData
  *
  * @return array
  */
 public function getData()
 {
  return $this->data;
 }

 /**
  * getErrors
  *
  * @return array
  */
 public function getErrors()
 {
  return $this->errors;
 }

 /**
  * getMessages
  *
  * @return array
  */
 public function getMessages()
 {
  return $this->messages;
 }

 /**
  * setRule
  *
  * @param string $key
  * @param string $value
  *
  * @return $this
  */
 public function setRule($key, $value)
 {
  $this->rules[$key] = $value;

  return $this;
 }

 /**
  * emptyRules
  *
  * @return $this
  */
 public function emptyRules()
 {
  $this->rules = array();

  return $this;
 }

 /**
  * sometimes
  *
  * @param string  $attribute
  * @param string|array $rules
  * @param callable  $callback
  *
  * @return $this
  */
 public function sometimes($attribute, $rules, callable $callback)
 {
  $this->validator->sometimes($attribute, $rules, $callback);

  return $this;
 }

 /**
  * resolver
  *
  * @param Closure $resolver
  *
  * @return $this
  */
 public function resolver(Closure $resolver)
 {
  Validator::resolver($resolver);

  return $this;
 }

 /**
  * replacer
  *
  * @param Closure $resolver
  *
  * @return $this
  */
 public function replacer($replace, Closure $resolver)
 {
  Validator::replacer($replace, $resolver);

  return $this;
 }

 /**
  * extendImplicit
  *
  * @param Closure $resolver
  *
  * @return $this
  */
 public function extendImplicit($extendImplicit, Closure $resolver)
 {
  Validator::extendImplicit($extendImplicit, $resolver);

  return $this;
 }

 /**
  * extend
  *
  * @param string   $rule
  * @param \Closure|string $extension
  * @param string   $message
  *
  * @return $this
  */
 public function extend($rule, $extension, $message = null)
 {
  Validator::extend($rule, $extension, $message);

  return $this;
 }

 /**
  * before (extend(),resolver())
  *
  * @return $this
  */
 public function before()
 {
 }

 /**
  * after(sometimes())
  *
  * @return $this
  */
 public function after()
 {
 }
}

新建中间件

<?php

namespace App\Http\Middleware;

use Closure;
use \Illuminate\Http\Request;

class ValidateAdminMiddleware
{
 /**
  * This namespace is applied to the controller routes in your routes file.
  *
  * In addition, it is set as the URL generator's root namespace.
  *
  * @var string
  */
 protected $namespace = 'App\Http\Validators';

 /**
  * Handle an incoming request.
  *
  * @param \Illuminate\Http\Request $request
  * @param \Closure     $next
  *
  * @return mixed
  */
 public function handle(Request $request, Closure $next, $validator = null)
 {
  if ($request->isMethod('POST')) {
   $type = $request->segment(1);
   if ($validator) {
    $validator = $this->namespace . '\\' . studly_case($type) . '\\' . studly_case($validator) . 'Validator';
    $validator = new $validator($request->all());

    if (!$validator->passes()) {
     if ($request->isAjax()) {
      return $validator->errors()->first();
     } else {
      return redirect()->back()
      ->withErrors($validator->getValidator())
      ->withInput();
     }
    }
   }
  }
  return $next($request);
 }
}

新建 TestTestValidator

<?php

namespace App\Http\Validators\Admin;

use App\Http\Validators\AbstractValidator;

class TestValidator extends AbstractValidator
{
 /**
  * Validation rules
  *
  * @var Array
  */
 protected $rules = array(
  'name' => ['required', 'test', 'min:1'],
 );

 /**
  * Validation messages
  *
  * @var Array
  */
 protected $messages = array(
  'name.required' => '必填',
  'name.min' => '最少1个字符',
  'name.test' => '测试',
 );

 /**
  * 自定义验证规则或者扩展Validator类
  */
 public function before()
 {
  $this->extend('test', function ($attribute, $value, $parameters) {
   return bool;
  });
 }
}

路由中如何使用

Route::post('/', ['middleware' => ['valiAdmin:Test'], 'uses' => 'IndexController@test']);

具体使用可以自行配置~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
多文件上载系统完整版
Oct 09 PHP
php模板之Phpbean的目录结构
Jan 10 PHP
php date与gmdate的获取日期的区别
Feb 08 PHP
fleaphp rolesNameField bug解决方法
Apr 23 PHP
php中实现记住密码下次自动登录的例子
Nov 06 PHP
php自定义hash函数实例
May 05 PHP
php源码分析之DZX1.5字符串截断函数cutstr用法
Jun 17 PHP
PHP的压缩函数实现:gzencode、gzdeflate和gzcompress的区别
Jan 27 PHP
postfixadmin忘记密码后的修改密码方法详解
Jul 20 PHP
php 使用fopen函数创建、打开文件详解及实例代码
Sep 24 PHP
php微信公众号开发之秒杀
Oct 20 PHP
PHP+Ajax实现的检测用户名功能简单示例
Feb 12 PHP
php使用curl模拟浏览器表单上传文件或者图片的方法
Nov 10 #PHP
safari下载文件自动加了html后缀问题
Nov 09 #PHP
centos7上编译安装php7以php-fpm方式连接apache
Nov 08 #PHP
PHP校验15位和18位身份证号的类封装
Nov 07 #PHP
php中如何执行linux命令详解
Nov 06 #PHP
laravel中的一些简单实用功能
Nov 03 #PHP
详解在YII2框架中使用UEditor编辑器发布文章
Nov 02 #PHP
You might like
基于PHP与XML的PDF文档生成技术
2006/10/09 PHP
PHP ? EasyUI DataGrid 资料存的方式介绍
2012/11/07 PHP
单点登录 Ucenter示例分析
2013/10/29 PHP
腾讯微博提示missing parameter errorcode 102 错误的解决方法
2014/12/22 PHP
kindeditor 加入七牛云上传的实例讲解
2017/11/12 PHP
PHP Primary script unknown 解决方法总结
2019/08/22 PHP
accesskey 提交
2006/06/26 Javascript
JavaScript实现网页上的浮动广告的简单方法
2013/06/14 Javascript
JS实现判断滚动条滚到页面底部并执行事件的方法
2014/12/18 Javascript
JS自定义对象实现Java中Map对象功能的方法
2015/01/20 Javascript
jQuery在ul中显示某个li索引号的方法
2015/03/17 Javascript
Vue.js常用指令汇总(v-if、v-for等)
2016/11/03 Javascript
vue2 中如何实现动态表单增删改查实例
2017/06/09 Javascript
浅谈Angular7 项目开发总结
2018/12/19 Javascript
微信小程序-form表单提交代码实例
2019/04/29 Javascript
微信小程序实现卡片层叠滑动效果
2019/06/21 Javascript
python获取一组数据里最大值max函数用法实例
2015/05/26 Python
使用Python从有道词典网页获取单词翻译
2016/07/03 Python
详解多线程Django程序耗尽数据库连接的问题
2018/10/08 Python
python实现祝福弹窗效果
2019/04/07 Python
python 中如何获取列表的索引
2019/07/02 Python
使用Python做垃圾分类的原理及实例代码附源码
2019/07/02 Python
Pyinstaller 打包exe教程及问题解决
2019/08/16 Python
Python 绘制可视化折线图
2020/07/22 Python
用Python制作mini翻译器的实现示例
2020/08/17 Python
python openCV实现摄像头获取人脸图片
2020/08/20 Python
英国的知名精品百货公司:House of Fraser(福来德)
2016/08/14 全球购物
alice McCALL官网:澳大利亚时尚品牌
2020/11/16 全球购物
股权转让协议书
2014/04/12 职场文书
电子装配专业毕业生求职信
2014/04/23 职场文书
党委书记个人对照检查材料
2014/09/15 职场文书
质量保证书格式
2015/02/27 职场文书
个人向公司借款协议书
2016/03/19 职场文书
公证书
2019/04/17 职场文书
python如何获取网络数据
2021/04/11 Python
教你怎么用python selenium实现自动化测试
2021/05/27 Python