关于脱离laravel框架使用Illuminate/Validation验证器
1.关于Illuminate/Validation验证器
Validation
类用于验证数据以及获取错误消息。
github地址:github.com/illuminate/validation
文档地址:https://docs.golaravel.com/docs/4.1/validation/
2.使用composer
如何使用composer:composer使用
packagist:https://packagist.org/package...
composer.json:
{ "require": { "illuminate/validation": "^5.5" } }
3.将vendor引入,自定义类
<?php /** * Created by PhpStorm. * User: Richard * Date: 2017/11/28 * Time: 10:57 */ namespace Rester; class Validator extends \Illuminate\Validation\Factory { private static $message = 'ok'; private static $headers = [ 'e' => 'rules/data is empty', 'na' => 'rules/data is not a array' ]; /*** * 创建实例 * * @return \Illuminate\Validation\Factory */ public static function getInstance() { static $validator = null; if ($validator === null) { $test_translation_path = __DIR__.'/lang'; $test_translation_locale = 'en'; $translation_file_loader = new \Illuminate\Translation\FileLoader(new \Illuminate\Filesystem\Filesystem, $test_translation_path); $translator = new \Illuminate\Translation\Translator($translation_file_loader, $test_translation_locale); $validator = new \Illuminate\Validation\Factory($translator); } return $validator; } /** * @param array $rules 验证规则 * @param array $data 验证数据 * @return bool */ public static function validators($rules=[],$data=[]) { if( empty($rules) || empty($data) ) { self::$message = self::$headers['e']; return false; } if(is_array($rules) && is_array($data)) { $v = self::vmake($rules,$data); if( $v->fails() ) { self::$message = $v->messages(); return false; } return true; } self::$message = self::$headers['na']; return false; } /** * 验证实例 * @param $rules * @param $data * @return \Illuminate\Validation\Validator */ private static function vmake($rules,$data) { $v = self::getInstance()->make($data,$rules); return $v; } /** * 获取错误消息 * @return string */ public static function getMessage() { return self::$message; } }
4.在项目中引入自定义类,调用验证
//验证数据demo public function insert() { //验证数据 $data = [ 'name' => '1' ]; //验证规则 $rules = [ 'name' => 'required|string|min:2|max:5', ]; if (Rester\Validator::validators($rules,$data)) { echo 'ok'; }else{ echo Rester\Validator::getMessage(); } }
至此, 大功告成~