1、关于Illuminate/Validation验证器
composer require illuminate/validation
2、composer.json 文件
{ "name": "song/test", "description": "validator.", "keywords": ["validator"], "license": "MIT", "type": "project", "autoload": { "psr-4": { "App\\": "app/" } }, "require": { "php": "^7.2", "illuminate/validation": "^7.16" }, "minimum-stability": "dev", "prefer-stable": true }
3、项目中使用,源码如下
require_once './vendor/autoload.php'; class Validator extends \Illuminate\Validation\Factory { /*** * 创建实例 * * @return \Illuminate\Validation\Factory */ public static function getInstance() { static $validator = null; if ($validator === null) { $test_translation_path = __DIR__ . '/lang'; $test_translation_locale = 'zh_cn'; $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; } } //验证数据 $data = [ 'title' => '123457', 'status' => 1 ]; //验证规则 $rules = [ 'title' => 'required|string|min:2|max:5', 'status' => 'required|integer' ]; //错误消息 $messages = [ 'title.max' => '标题不能大于5位' ]; //属性名称 $attributes = [ 'title' => '名称', 'status' => '状态', ]; $validator = Validator::getInstance()->make($data, $rules, $messages, $attributes); if ($validator->fails()) { echo 'fail'; }else{ echo 'ok'; } echo "\n"; //输出错误消息 print_r($validator->errors()->first());