TP中使用laravel那一套验证
---恢复内容开始---
1,tp5项目下新建一个extends目录,同时在入口文件index.php配置
define('EXTEND_PATH', '../extend/');
结果:

2,加载laravel里面涉及的illuminate包,更改composer。json文件 以后(如下),composer update
{
"name": "topthink/think",
"description": "the new thinkphp framework",
"type": "project",
"keywords": [
"framework",
"thinkphp",
"ORM"
],
"homepage": "http://thinkphp.cn/",
"license": "Apache-2.0",
"authors": [
{
"name": "liu21st",
"email": "liu21st@gmail.com"
}
],
"repositories": {
"packagist": {
"type": "composer",
"url": "https://packagist.phpcomposer.com"
}
},
"require": {
"php": ">=5.4.0",
"topthink/framework": "^5.0",
"topthink/think-image": "^1.0",
"topthink/think-captcha": "^1.0",
"topthink/think-mongo": "^1.0",
"topthink/think-migration": "^1.0",
"topthink/think-angular": "^1.0",
"topthink/think-sae": "^1.0",
"topthink/think-worker": "^1.0",
"topthink/think-queue": "^1.0",
"topthink/think-testing": "^1.0",
"illuminate/validation": "^5.5",
"illuminate/translation": "5.5.*",
"illuminate/database": "^5.5",
"douyasi/identity-card": "~2.0"
},
"extra": {
"think-path": "thinkphp"
},
"config": {
"preferred-install": "dist"
}
}
3,在extend文件夹下面新建一个Validator.php
<?php
namespace validator;
//use exception\ValidatorException;
use Illuminate\Database\Capsule\Manager;
use Illuminate\Validation;
use Illuminate\Filesystem;
use Illuminate\Translation;
use Illuminate\Validation\DatabasePresenceVerifier;
use think\Exception;
use DB;
use Douyasi\IdentityCard\ID; class Validator
{
static $factory = null; /**
* @param $data
* @param $rules
* @return array
* @throws ValidatorException
*/
public static function make($data, $rules)
{
$is_default = [];
foreach($rules as $key=>$x)
{
$rules[$key] = preg_replace('/\|default\:[^\|]+/', '', $x, 1, $match);
if($match)
{
preg_match('/\|default:([^\|]+)/', $x, $m);
if(isset($m[1]))
{
$is_default[$key] = $m[1];
}
else
{
$is_default[$key] = null;
}
}
else
{
$is_default[$key] = null;
}
}
// var_dump($is_default);die;
if(self::$factory === null)
{
$filesystem = new Filesystem\Filesystem();
$fileLoader = new Translation\FileLoader($filesystem, THINK_PATH.'/../application/extra/');
$translator = new Translation\Translator($fileLoader, '/');
$factory = new Validation\Factory($translator); $database = [
'driver' => 'mysql',
'host' => env('DB_HOST', '192.168.40.8'),
'database' => env('DB_NAME', 'huolicai'),
'username' => env('DB_USER', 'root'),
'password' => env('DB_PASS', 'Abc@123456'),
'port' => env('DB_PORT', '3306'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
];
$connection = new Manager();
$connection->addConnection($database);
$connection->bootEloquent();
$connection->setAsGlobal();
$factory->setPresenceVerifier(new DatabasePresenceVerifier($connection->getDatabaseManager())); $factory->extend('list', function ($attribute, $value, $parameters, $validator) {
if(!is_array($value)) $value = explode(',', $value);
foreach($value as $item){
if($parameters[0] == 'integer' && !is_numeric($item))
throw new ValidatorException($attribute . ' 的每项必须为'.$parameters[0].'的类型', ValidatorException::BAD_VALIDATOR_PARAMS);
}
return true;
}); $factory->extend('csrf', function ($attribute, $value, $parameters, $validator) {
return $value == md5('SECRET.XXX'.\think\Request::instance()->ip());
}); $factory->extend('cellphone', function ($attribute, $value, $parameters, $validator) {
return preg_match('/^1(3|4|5|7|8|9)\d{9}$/', $value);
}); $factory->extend('idcard', function ($attribute, $value, $parameters, $validator) {
$ID = new ID();
return $ID->validateIDCard($value);
}); $factory->extend('length', function ($attribute, $value, $parameters, $validator) {
return strlen($value) == ($parameters[0]??0);
}); $factory->extend('length_between', function ($attribute, $value, $parameters, $validator) {
return (strlen($value) > $parameters[0]??0 )&&(strlen($value) < $parameters[1] ?? 0);
}); $factory->extend('bankcard', function ($attribute, $value, $parameters, $validator) {
try{
$card = \Bank::card($value);
}catch(\Exception $e){
# echo 'error_1';exit();
throw new ValidatorException('获取银行卡信息失败,请检查并重试', ValidatorException::BAD_VALIDATOR_PARAMS);
} if(!isset($card['validated']))
# echo 'error_2';exit();
throw new ValidatorException('获取银行卡信息失败,请检查并重试', ValidatorException::BAD_VALIDATOR_PARAMS);
/*
if(!$card['validated'])
throw new ValidatorException('银行卡无效', ValidatorException::BAD_VALIDATOR_PARAMS);
*/
if($card['cardType'] == 'CC')
throw new ValidatorException('不支持信用卡', ValidatorException::BAD_VALIDATOR_PARAMS); if(!isset(config('bank')[$card['bank']]))
throw new ValidatorException('不支持'.($card['bankName'] ?? $card['bank'] ?? '这张').'银行卡', ValidatorException::BAD_VALIDATOR_PARAMS); return true;
}); $factory->extend('float_digits', function ($attribute, $value, $parameters, $validator) {
$value = (float) $value;
$string = (string) $value;
$divided = explode('.', $string);
if(!count($parameters) == 2)
throw new ValidatorException(null, ValidatorException::BAD_VALIDATOR_PARAMS); if(!isset($divided[1]) && $parameters[0] == 0)
return true; if(isset($divided[1]) && strlen($divided[1]) <= $parameters[1] && strlen($divided[1]) >= $parameters[0])
return true; return false;
}); $factory->extend('exists_in', function ($attribute, $value, $parameters, $validator) {
if(($parameters[0] == true && trim($value)) || ($parameters[0] == false) ){
if(count($parameters) < 2) $parameters[1] = 'id'; $column = $parameters[1];
$exists = \think\Db::table($parameters[0])->where([$column => $value]);
if(isset($parameters[2]))
{
parse_str($parameters[2], $xx);
if($xx)
{
$exists = $exists->where($xx);
}
}
$attribute_name = config('validation.attributes')[$attribute] ?? $attribute; $exists = $exists->find();
if(!$exists)
throw new ValidatorException($attribute_name.' 不存在', ValidatorException::BAD_VALIDATOR_PARAMS);
}
return true;
}); $factory->extend('unique_in', function ($attribute, $value, $parameters, $validator) {
if(($parameters[0] == true && trim($value)) || ($parameters[0] == false) ){
if(count($parameters) < 2) $parameters[1] = 'id'; $column = $parameters[1];
$exists = \think\Db::table($parameters[0])->where([$column => $value]);
if(isset($parameters[2]))
{
parse_str($parameters[2], $xx);
if($xx)
{
$exists = $exists->where($xx);
}
}
$attribute_name = config('validation.attributes')[$attribute] ?? $attribute; $exists = $exists->find();
if($exists)
throw new ValidatorException($attribute_name.' 已存在', ValidatorException::BAD_VALIDATOR_PARAMS);
}
return true;
}); $factory->extend('exists_if', function ($attribute, $value, $parameters, $validator) {
if(($parameters[0] == true && trim($value)) || ($parameters[0] == false && !trim($value)) ){
if(count($parameters) < 3) $parameters[2] = 'id'; $column = $parameters[2];
$attribute_name = config('validation.attributes')[$attribute] ?? $attribute; $exists = \think\Db::table($parameters[1])->where([$column => $value])->find();
if(!$exists)
throw new ValidatorException($attribute_name.' 不存在', ValidatorException::BAD_VALIDATOR_PARAMS);
}
return true;
}); $factory->extend('default', function ($attribute, $value, $parameters, $validator) {
return true;
}); $factory->extend('unique_if', function ($attribute, $value, $parameters, $validator) {
if(($parameters[0] == true && trim($value)) || ($parameters[0] == false && !trim($value)) ){
if(count($parameters) < 3) $parameters[2] = 'id'; $column = $parameters[2];
$attribute_name = config('validation.attributes')[$attribute] ?? $attribute; $exists = \think\Db::table($parameters[1])->where([$column => $value])->find();
if($exists)
throw new ValidatorException($attribute_name.' 已存在', ValidatorException::BAD_VALIDATOR_PARAMS);
}
return true;
}); $factory->extend('null_if', function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
$cond = $validator->getData()[$parameters[0]];
$match = false;
for($i = 1; $i < count($parameters); $i++)
{
if($cond == $parameters[$i]){
$match = true;
break;
}
}
if($match)
{
if(!empty($value) && $value !== 0 && $value !== '0') return false;
}
return true;
}); self::$factory = $factory;
}else{
$factory = self::$factory;
} $messages = config('validation.custom');
$validator = $factory->make($data, $rules, $messages);
if($validator->fails())
{
throw new Exception(implode(',', $validator->errors()->all()), Exception::BAD_PARAMS);
} $return = [];
foreach($rules as $key=>$x)
{
$value = $data[$key] ?? $is_default[$key] ?? '';
if(($value === NULL || $value === "") && $is_default[$key] !== NULL)
{
$value = $is_default[$key];
}
if(null === $value || '' === $value)
{
}
if(preg_match('/list\:/', $rules[$key]))
{
if(is_null($value)) $value = '';
$value = explode(',', $value);
}
$return[] = $value;
} return $return;
}
}
5,在controller里面写一个方法
<?php
namespace app\index\controller; use validator\Validator; class Index
{
public function test1()
{
$handler = new Validator();
$a = $handler->make(['user'=>142, 'phone'=>1,'name'=>'kevin'],[
'user'=>'required|max:2',
'phone'=>'required',
'name'=>'required',
// 'id'=>'required|idcard'
],[
'phone.required' => 'phone不能为空',
'name.required' => '姓名不能为空'
]); echo "验证通过";
6,结果

7,如何新增验证方法 : 大(比如增加一个idcard验证身份证的方法)
第一步:在validator.php修改

代码如下:
$factory->extend('idcard', function ($attribute, $value, $parameters, $validator) {
$ID = new ID();
return $ID->validateIDCard($value);
});
注意:为了能验证身份证,这里利用了第三方的包

结果演示:

TP中使用laravel那一套验证的更多相关文章
- Laravel 中自定义 手机号和身份证号验证
首先在 Providers\AppServiceProvider.php 文件中自定义 手机号和身份证号验证 // AppServiceProvider.php 文件 <?php namespa ...
- 【干货】Laravel --Validate (表单验证) 使用实例
前言 : Laravel 提供了多种方法来验证应用输入数据.默认情况下,Laravel 的控制器基类使用ValidatesRequests trait,该trait提供了便利的方法通过各种功能强大的验 ...
- 仿联想商城laravel实战---4、验证(lavarel的表单验证如何使用)
仿联想商城laravel实战---4.验证(lavarel的表单验证如何使用) 一.总结 一句话总结: 验证规则和验证信息的数组:在控制器的方法中 1.注册页面中的用户名正确(比如是否重名,字段长度是 ...
- laravel的Validation检索验证错误消息
基本用法 处理错误消息 错误消息和视图 可用的验证规则 有条件地添加规则 自定义错误消息 自定义验证规则 基本用法 Laravel提供了一个简单.方便的工具,用于验证数据并通过validation类检 ...
- 再说表单验证,在Web Api中使用ModelState进行接口参数验证
写在前面 上篇文章中说到了表单验证的问题,然后尝试了一下用扩展方法实现链式编程,评论区大家讨论的非常激烈也推荐了一些很强大的验证插件.其中一位园友提到了说可以使用MVC的ModelState,因为之前 ...
- tp中使用分页技术
1 public function showList() { $m_ld = D ( 'guangxi_ld' ); $page = I ( 'get.p', 1 ); // 在配置中获取分页值 $p ...
- 在 Java 代码中对 Kerberos 主体进行身份验证
转载请注明出处:http://www.cnblogs.com/xiaodf/ 本文举例说明如何使用 org.apache.hadoop.security.UserGroupInformation 类在 ...
- SpringMVC中使用Jcaptcha实现校验码验证
SpringMVC中使用Jcaptcha实现校验码验证:http://www.tuicool.com/articles/rMzAFj 本文将使用Jcaptcha实现校验码验证,并演示在Spring/S ...
- asp.net中常用的几种身份验证方式
转载:http://www.cnblogs.com/dinglang/archive/2012/06/03/2532664.html 前言 在B/S系统开发中,经常需要使用"身份验证&q ...
随机推荐
- UVa 508 Morse Mismatches (模糊暴力)
题意:莫尔斯电码,输入若干个字母的Morse编号,一个字典和若干编码.对于每个编号,判断它可能的是哪个单词, 如果有多个单词精确匹配,输出第一个单词并加一个“!”:如果无法精确匹配,那么在编码尾部增加 ...
- spring mvc 静态资源版本控制
spring bean 文件中增加 <bean class="cn.zno.smse.common.context.VersionServletContext">< ...
- POJ1410_还是没考虑全面——线段是否与矩形有共同的垂直投影
题意如题目 有几个点1.怪我没读好题目:给出的矩形两个端点不一定都是左上右下,但是肯定能勾勒出一个矩形. 2.现在才发现很多线段相交的判断我都没有仔细考虑这一个问题 bool ssinsert(Poi ...
- poj2462
看八戒在做这个题,我也做了做.. 坑很多,还是要注意细节.不得不吐槽,难道又到了计算几何只能套模板否则就一串WA的情况了么! 要不是八戒做出来了,这题我估计我也就扔到这里了..哥不服啊~所以得做出来! ...
- Mysql工作記錄之修改默認存儲引擎及重設root用戶密碼
1>修改默認存儲引擎方法 修改配置文件,然後重啟mysql服務: [root@CHW mysql]# cat /etc/my.cnf [my ...
- [leetcode] 15. Plus One
这道题其实让我意识到了我的英文水平还有待加强.... 题目如下: Given a non-negative number represented as an array of digits, plus ...
- Android 将APK文件安装到AVD中并分析其界面结构
配置环境变量 将android sdk 中的android-sdk\tools .android-sdk\platform-tools 添加到windows环境变量中.用于打开android sdk中 ...
- Jersey Client传递中文参数
客户端需要客户端的包: <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jerse ...
- 数据库选项--ALTER DATABASE WITH 选项
指定当数据库从一种状态转换到另一种状态时,何时回滚未完成的事务. 如果终止子句被忽略,则当数据库中存在任何锁时,ALTER DATABASE 语句将无限期等待. 只能指定一条终止子句,而且该子句应跟在 ...
- BitAdminCore框架更新日志20180529
索引 NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/coo ...