Validate.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\exception\ClassNotFoundException;
  13. class Validate
  14. {
  15. // 实例
  16. protected static $instance;
  17. // 自定义的验证类型
  18. protected static $type = [];
  19. // 验证类型别名
  20. protected $alias = [
  21. '>' => 'gt', '>=' => 'egt', '<' => 'lt', '<=' => 'elt', '=' => 'eq', 'same' => 'eq',
  22. ];
  23. // 当前验证的规则
  24. protected $rule = [];
  25. // 验证提示信息
  26. protected $message = [];
  27. // 验证字段描述
  28. protected $field = [];
  29. // 验证规则默认提示信息
  30. protected static $typeMsg = [
  31. 'require' => ':attribute require',
  32. 'number' => ':attribute must be numeric',
  33. 'integer' => ':attribute must be integer',
  34. 'float' => ':attribute must be float',
  35. 'boolean' => ':attribute must be bool',
  36. 'email' => ':attribute not a valid email address',
  37. 'mobile' => ':attribute not a valid mobile',
  38. 'array' => ':attribute must be a array',
  39. 'accepted' => ':attribute must be yes,on or 1',
  40. 'date' => ':attribute not a valid datetime',
  41. 'file' => ':attribute not a valid file',
  42. 'image' => ':attribute not a valid image',
  43. 'alpha' => ':attribute must be alpha',
  44. 'alphaNum' => ':attribute must be alpha-numeric',
  45. 'alphaDash' => ':attribute must be alpha-numeric, dash, underscore',
  46. 'activeUrl' => ':attribute not a valid domain or ip',
  47. 'chs' => ':attribute must be chinese',
  48. 'chsAlpha' => ':attribute must be chinese or alpha',
  49. 'chsAlphaNum' => ':attribute must be chinese,alpha-numeric',
  50. 'chsDash' => ':attribute must be chinese,alpha-numeric,underscore, dash',
  51. 'url' => ':attribute not a valid url',
  52. 'ip' => ':attribute not a valid ip',
  53. 'dateFormat' => ':attribute must be dateFormat of :rule',
  54. 'in' => ':attribute must be in :rule',
  55. 'notIn' => ':attribute be notin :rule',
  56. 'between' => ':attribute must between :1 - :2',
  57. 'notBetween' => ':attribute not between :1 - :2',
  58. 'length' => 'size of :attribute must be :rule',
  59. 'max' => 'max size of :attribute must be :rule',
  60. 'min' => 'min size of :attribute must be :rule',
  61. 'after' => ':attribute cannot be less than :rule',
  62. 'before' => ':attribute cannot exceed :rule',
  63. 'expire' => ':attribute not within :rule',
  64. 'allowIp' => 'access IP is not allowed',
  65. 'denyIp' => 'access IP denied',
  66. 'confirm' => ':attribute out of accord with :2',
  67. 'different' => ':attribute cannot be same with :2',
  68. 'egt' => ':attribute must greater than or equal :rule',
  69. 'gt' => ':attribute must greater than :rule',
  70. 'elt' => ':attribute must less than or equal :rule',
  71. 'lt' => ':attribute must less than :rule',
  72. 'eq' => ':attribute must equal :rule',
  73. 'unique' => ':attribute has exists',
  74. 'regex' => ':attribute not conform to the rules',
  75. 'method' => 'invalid Request method',
  76. 'token' => 'invalid token',
  77. 'fileSize' => 'filesize not match',
  78. 'fileExt' => 'extensions to upload is not allowed',
  79. 'fileMime' => 'mimetype to upload is not allowed',
  80. ];
  81. // 当前验证场景
  82. protected $currentScene = null;
  83. // 正则表达式 regex = ['zip'=>'\d{6}',...]
  84. protected $regex = [];
  85. // 验证场景 scene = ['edit'=>'name1,name2,...']
  86. protected $scene = [];
  87. // 验证失败错误信息
  88. protected $error = [];
  89. // 批量验证
  90. protected $batch = false;
  91. /**
  92. * 构造函数
  93. * @access public
  94. * @param array $rules 验证规则
  95. * @param array $message 验证提示信息
  96. * @param array $field 验证字段描述信息
  97. */
  98. public function __construct(array $rules = [], $message = [], $field = [])
  99. {
  100. $this->rule = array_merge($this->rule, $rules);
  101. $this->message = array_merge($this->message, $message);
  102. $this->field = array_merge($this->field, $field);
  103. }
  104. /**
  105. * 实例化验证
  106. * @access public
  107. * @param array $rules 验证规则
  108. * @param array $message 验证提示信息
  109. * @param array $field 验证字段描述信息
  110. * @return Validate
  111. */
  112. public static function make($rules = [], $message = [], $field = [])
  113. {
  114. if (is_null(self::$instance)) {
  115. self::$instance = new self($rules, $message, $field);
  116. }
  117. return self::$instance;
  118. }
  119. /**
  120. * 添加字段验证规则
  121. * @access protected
  122. * @param string|array $name 字段名称或者规则数组
  123. * @param mixed $rule 验证规则
  124. * @return Validate
  125. */
  126. public function rule($name, $rule = '')
  127. {
  128. if (is_array($name)) {
  129. $this->rule = array_merge($this->rule, $name);
  130. } else {
  131. $this->rule[$name] = $rule;
  132. }
  133. return $this;
  134. }
  135. /**
  136. * 注册验证(类型)规则
  137. * @access public
  138. * @param string $type 验证规则类型
  139. * @param mixed $callback callback方法(或闭包)
  140. * @return void
  141. */
  142. public static function extend($type, $callback = null)
  143. {
  144. if (is_array($type)) {
  145. self::$type = array_merge(self::$type, $type);
  146. } else {
  147. self::$type[$type] = $callback;
  148. }
  149. }
  150. /**
  151. * 设置验证规则的默认提示信息
  152. * @access protected
  153. * @param string|array $type 验证规则类型名称或者数组
  154. * @param string $msg 验证提示信息
  155. * @return void
  156. */
  157. public static function setTypeMsg($type, $msg = null)
  158. {
  159. if (is_array($type)) {
  160. self::$typeMsg = array_merge(self::$typeMsg, $type);
  161. } else {
  162. self::$typeMsg[$type] = $msg;
  163. }
  164. }
  165. /**
  166. * 设置提示信息
  167. * @access public
  168. * @param string|array $name 字段名称
  169. * @param string $message 提示信息
  170. * @return Validate
  171. */
  172. public function message($name, $message = '')
  173. {
  174. if (is_array($name)) {
  175. $this->message = array_merge($this->message, $name);
  176. } else {
  177. $this->message[$name] = $message;
  178. }
  179. return $this;
  180. }
  181. /**
  182. * 设置验证场景
  183. * @access public
  184. * @param string|array $name 场景名或者场景设置数组
  185. * @param mixed $fields 要验证的字段
  186. * @return Validate
  187. */
  188. public function scene($name, $fields = null)
  189. {
  190. if (is_array($name)) {
  191. $this->scene = array_merge($this->scene, $name);
  192. }if (is_null($fields)) {
  193. // 设置当前场景
  194. $this->currentScene = $name;
  195. } else {
  196. // 设置验证场景
  197. $this->scene[$name] = $fields;
  198. }
  199. return $this;
  200. }
  201. /**
  202. * 判断是否存在某个验证场景
  203. * @access public
  204. * @param string $name 场景名
  205. * @return bool
  206. */
  207. public function hasScene($name)
  208. {
  209. return isset($this->scene[$name]);
  210. }
  211. /**
  212. * 设置批量验证
  213. * @access public
  214. * @param bool $batch 是否批量验证
  215. * @return Validate
  216. */
  217. public function batch($batch = true)
  218. {
  219. $this->batch = $batch;
  220. return $this;
  221. }
  222. /**
  223. * 数据自动验证
  224. * @access public
  225. * @param array $data 数据
  226. * @param mixed $rules 验证规则
  227. * @param string $scene 验证场景
  228. * @return bool
  229. */
  230. public function check($data, $rules = [], $scene = '')
  231. {
  232. $this->error = [];
  233. if (empty($rules)) {
  234. // 读取验证规则
  235. $rules = $this->rule;
  236. }
  237. // 分析验证规则
  238. $scene = $this->getScene($scene);
  239. if (is_array($scene)) {
  240. // 处理场景验证字段
  241. $change = [];
  242. $array = [];
  243. foreach ($scene as $k => $val) {
  244. if (is_numeric($k)) {
  245. $array[] = $val;
  246. } else {
  247. $array[] = $k;
  248. $change[$k] = $val;
  249. }
  250. }
  251. }
  252. foreach ($rules as $key => $item) {
  253. // field => rule1|rule2... field=>['rule1','rule2',...]
  254. if (is_numeric($key)) {
  255. // [field,rule1|rule2,msg1|msg2]
  256. $key = $item[0];
  257. $rule = $item[1];
  258. if (isset($item[2])) {
  259. $msg = is_string($item[2]) ? explode('|', $item[2]) : $item[2];
  260. } else {
  261. $msg = [];
  262. }
  263. } else {
  264. $rule = $item;
  265. $msg = [];
  266. }
  267. if (strpos($key, '|')) {
  268. // 字段|描述 用于指定属性名称
  269. list($key, $title) = explode('|', $key);
  270. } else {
  271. $title = isset($this->field[$key]) ? $this->field[$key] : $key;
  272. }
  273. // 场景检测
  274. if (!empty($scene)) {
  275. if ($scene instanceof \Closure && !call_user_func_array($scene, [$key, $data])) {
  276. continue;
  277. } elseif (is_array($scene)) {
  278. if (!in_array($key, $array)) {
  279. continue;
  280. } elseif (isset($change[$key])) {
  281. // 重载某个验证规则
  282. $rule = $change[$key];
  283. }
  284. }
  285. }
  286. // 获取数据 支持二维数组
  287. $value = $this->getDataValue($data, $key);
  288. // 字段验证
  289. if ($rule instanceof \Closure) {
  290. // 匿名函数验证 支持传入当前字段和所有字段两个数据
  291. $result = call_user_func_array($rule, [$value, $data]);
  292. } else {
  293. $result = $this->checkItem($key, $value, $rule, $data, $title, $msg);
  294. }
  295. if (true !== $result) {
  296. // 没有返回true 则表示验证失败
  297. if (!empty($this->batch)) {
  298. // 批量验证
  299. if (is_array($result)) {
  300. $this->error = array_merge($this->error, $result);
  301. } else {
  302. $this->error[$key] = $result;
  303. }
  304. } else {
  305. $this->error = $result;
  306. return false;
  307. }
  308. }
  309. }
  310. return !empty($this->error) ? false : true;
  311. }
  312. /**
  313. * 根据验证规则验证数据
  314. * @access protected
  315. * @param mixed $value 字段值
  316. * @param mixed $rules 验证规则
  317. * @return bool
  318. */
  319. protected function checkRule($value, $rules)
  320. {
  321. if ($rules instanceof \Closure) {
  322. return call_user_func_array($rules, [$value]);
  323. } elseif (is_string($rules)) {
  324. $rules = explode('|', $rules);
  325. }
  326. foreach ($rules as $key => $rule) {
  327. if ($rule instanceof \Closure) {
  328. $result = call_user_func_array($rule, [$value]);
  329. } else {
  330. // 判断验证类型
  331. list($type, $rule) = $this->getValidateType($key, $rule);
  332. $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type];
  333. $result = call_user_func_array($callback, [$value, $rule]);
  334. }
  335. if (true !== $result) {
  336. return $result;
  337. }
  338. }
  339. return true;
  340. }
  341. /**
  342. * 验证单个字段规则
  343. * @access protected
  344. * @param string $field 字段名
  345. * @param mixed $value 字段值
  346. * @param mixed $rules 验证规则
  347. * @param array $data 数据
  348. * @param string $title 字段描述
  349. * @param array $msg 提示信息
  350. * @return mixed
  351. */
  352. protected function checkItem($field, $value, $rules, $data, $title = '', $msg = [])
  353. {
  354. // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...]
  355. if (is_string($rules)) {
  356. $rules = explode('|', $rules);
  357. }
  358. $i = 0;
  359. foreach ($rules as $key => $rule) {
  360. if ($rule instanceof \Closure) {
  361. $result = call_user_func_array($rule, [$value, $data]);
  362. $info = is_numeric($key) ? '' : $key;
  363. } else {
  364. // 判断验证类型
  365. list($type, $rule, $info) = $this->getValidateType($key, $rule);
  366. // 如果不是require 有数据才会行验证
  367. if (0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) {
  368. // 验证类型
  369. $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type];
  370. // 验证数据
  371. $result = call_user_func_array($callback, [$value, $rule, $data, $field, $title]);
  372. } else {
  373. $result = true;
  374. }
  375. }
  376. if (false === $result) {
  377. // 验证失败 返回错误信息
  378. if (isset($msg[$i])) {
  379. $message = $msg[$i];
  380. if (is_string($message) && strpos($message, '{%') === 0) {
  381. $message = Lang::get(substr($message, 2, -1));
  382. }
  383. } else {
  384. $message = $this->getRuleMsg($field, $title, $info, $rule);
  385. }
  386. return $message;
  387. } elseif (true !== $result) {
  388. // 返回自定义错误信息
  389. if (is_string($result) && false !== strpos($result, ':')) {
  390. $result = str_replace([':attribute', ':rule'], [$title, (string) $rule], $result);
  391. }
  392. return $result;
  393. }
  394. $i++;
  395. }
  396. return $result;
  397. }
  398. /**
  399. * 获取当前验证类型及规则
  400. * @access public
  401. * @param mixed $key
  402. * @param mixed $rule
  403. * @return array
  404. */
  405. protected function getValidateType($key, $rule)
  406. {
  407. // 判断验证类型
  408. if (!is_numeric($key)) {
  409. return [$key, $rule, $key];
  410. }
  411. if (strpos($rule, ':')) {
  412. list($type, $rule) = explode(':', $rule, 2);
  413. if (isset($this->alias[$type])) {
  414. // 判断别名
  415. $type = $this->alias[$type];
  416. }
  417. $info = $type;
  418. } elseif (method_exists($this, $rule)) {
  419. $type = $rule;
  420. $info = $rule;
  421. $rule = '';
  422. } else {
  423. $type = 'is';
  424. $info = $rule;
  425. }
  426. return [$type, $rule, $info];
  427. }
  428. /**
  429. * 验证是否和某个字段的值一致
  430. * @access protected
  431. * @param mixed $value 字段值
  432. * @param mixed $rule 验证规则
  433. * @param array $data 数据
  434. * @param string $field 字段名
  435. * @return bool
  436. */
  437. protected function confirm($value, $rule, $data, $field = '')
  438. {
  439. if ('' == $rule) {
  440. if (strpos($field, '_confirm')) {
  441. $rule = strstr($field, '_confirm', true);
  442. } else {
  443. $rule = $field . '_confirm';
  444. }
  445. }
  446. return $this->getDataValue($data, $rule) === $value;
  447. }
  448. /**
  449. * 验证是否和某个字段的值是否不同
  450. * @access protected
  451. * @param mixed $value 字段值
  452. * @param mixed $rule 验证规则
  453. * @param array $data 数据
  454. * @return bool
  455. */
  456. protected function different($value, $rule, $data)
  457. {
  458. return $this->getDataValue($data, $rule) != $value;
  459. }
  460. /**
  461. * 验证是否大于等于某个值
  462. * @access protected
  463. * @param mixed $value 字段值
  464. * @param mixed $rule 验证规则
  465. * @param array $data 数据
  466. * @return bool
  467. */
  468. protected function egt($value, $rule, $data)
  469. {
  470. $val = $this->getDataValue($data, $rule);
  471. return !is_null($val) && $value >= $val;
  472. }
  473. /**
  474. * 验证是否大于某个值
  475. * @access protected
  476. * @param mixed $value 字段值
  477. * @param mixed $rule 验证规则
  478. * @param array $data 数据
  479. * @return bool
  480. */
  481. protected function gt($value, $rule, $data)
  482. {
  483. $val = $this->getDataValue($data, $rule);
  484. return !is_null($val) && $value > $val;
  485. }
  486. /**
  487. * 验证是否小于等于某个值
  488. * @access protected
  489. * @param mixed $value 字段值
  490. * @param mixed $rule 验证规则
  491. * @param array $data 数据
  492. * @return bool
  493. */
  494. protected function elt($value, $rule, $data)
  495. {
  496. $val = $this->getDataValue($data, $rule);
  497. return !is_null($val) && $value <= $val;
  498. }
  499. /**
  500. * 验证是否小于某个值
  501. * @access protected
  502. * @param mixed $value 字段值
  503. * @param mixed $rule 验证规则
  504. * @param array $data 数据
  505. * @return bool
  506. */
  507. protected function lt($value, $rule, $data)
  508. {
  509. $val = $this->getDataValue($data, $rule);
  510. return !is_null($val) && $value < $val;
  511. }
  512. /**
  513. * 验证是否等于某个值
  514. * @access protected
  515. * @param mixed $value 字段值
  516. * @param mixed $rule 验证规则
  517. * @return bool
  518. */
  519. protected function eq($value, $rule)
  520. {
  521. return $value == $rule;
  522. }
  523. /**
  524. * 验证字段值是否为有效格式
  525. * @access protected
  526. * @param mixed $value 字段值
  527. * @param string $rule 验证规则
  528. * @param array $data 验证数据
  529. * @return bool
  530. */
  531. protected function is($value, $rule, $data = [])
  532. {
  533. switch ($rule) {
  534. case 'require':
  535. // 必须
  536. $result = !empty($value) || '0' == $value;
  537. break;
  538. case 'accepted':
  539. // 接受
  540. $result = in_array($value, ['1', 'on', 'yes']);
  541. break;
  542. case 'date':
  543. // 是否是一个有效日期
  544. $result = false !== strtotime($value);
  545. break;
  546. case 'alpha':
  547. // 只允许字母
  548. $result = $this->regex($value, '/^[A-Za-z]+$/');
  549. break;
  550. case 'alphaNum':
  551. // 只允许字母和数字
  552. $result = $this->regex($value, '/^[A-Za-z0-9]+$/');
  553. break;
  554. case 'alphaDash':
  555. // 只允许字母、数字和下划线 破折号
  556. $result = $this->regex($value, '/^[A-Za-z0-9\-\_]+$/');
  557. break;
  558. case 'chs':
  559. // 只允许汉字
  560. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}]+$/u');
  561. break;
  562. case 'chsAlpha':
  563. // 只允许汉字、字母
  564. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u');
  565. break;
  566. case 'chsAlphaNum':
  567. // 只允许汉字、字母和数字
  568. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u');
  569. break;
  570. case 'chsDash':
  571. // 只允许汉字、字母、数字和下划线_及破折号-
  572. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u');
  573. break;
  574. case 'activeUrl':
  575. // 是否为有效的网址
  576. $result = checkdnsrr($value);
  577. break;
  578. case 'ip':
  579. // 是否为IP地址
  580. $result = $this->filter($value, [FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6]);
  581. break;
  582. case 'url':
  583. // 是否为一个URL地址
  584. $result = $this->filter($value, FILTER_VALIDATE_URL);
  585. break;
  586. case 'float':
  587. // 是否为float
  588. $result = $this->filter($value, FILTER_VALIDATE_FLOAT);
  589. break;
  590. case 'number':
  591. $result = is_numeric($value);
  592. break;
  593. case 'integer':
  594. // 是否为整型
  595. $result = $this->filter($value, FILTER_VALIDATE_INT);
  596. break;
  597. case 'email':
  598. // 是否为邮箱地址
  599. $result = $this->filter($value, FILTER_VALIDATE_EMAIL);
  600. break;
  601. case 'boolean':
  602. // 是否为布尔值
  603. $result = in_array($value, [true, false, 0, 1, '0', '1'], true);
  604. break;
  605. case 'array':
  606. // 是否为数组
  607. $result = is_array($value);
  608. break;
  609. case 'file':
  610. $result = $value instanceof File;
  611. break;
  612. case 'image':
  613. $result = $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]);
  614. break;
  615. case 'token':
  616. $result = $this->token($value, '__token__', $data);
  617. break;
  618. default:
  619. if (isset(self::$type[$rule])) {
  620. // 注册的验证规则
  621. $result = call_user_func_array(self::$type[$rule], [$value]);
  622. } else {
  623. // 正则验证
  624. $result = $this->regex($value, $rule);
  625. }
  626. }
  627. return $result;
  628. }
  629. // 判断图像类型
  630. protected function getImageType($image)
  631. {
  632. if (function_exists('exif_imagetype')) {
  633. return exif_imagetype($image);
  634. } else {
  635. try {
  636. $info = getimagesize($image);
  637. return $info ? $info[2] : false;
  638. } catch (\Exception $e) {
  639. return false;
  640. }
  641. }
  642. }
  643. /**
  644. * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
  645. * @access protected
  646. * @param mixed $value 字段值
  647. * @param mixed $rule 验证规则
  648. * @return bool
  649. */
  650. protected function activeUrl($value, $rule)
  651. {
  652. if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
  653. $rule = 'MX';
  654. }
  655. return checkdnsrr($value, $rule);
  656. }
  657. /**
  658. * 验证是否有效IP
  659. * @access protected
  660. * @param mixed $value 字段值
  661. * @param mixed $rule 验证规则 ipv4 ipv6
  662. * @return bool
  663. */
  664. protected function ip($value, $rule)
  665. {
  666. if (!in_array($rule, ['ipv4', 'ipv6'])) {
  667. $rule = 'ipv4';
  668. }
  669. return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]);
  670. }
  671. /**
  672. * 验证上传文件后缀
  673. * @access protected
  674. * @param mixed $file 上传文件
  675. * @param mixed $rule 验证规则
  676. * @return bool
  677. */
  678. protected function fileExt($file, $rule)
  679. {
  680. if (is_array($file)) {
  681. foreach ($file as $item) {
  682. if (!($item instanceof File) || !$item->checkExt($rule)) {
  683. return false;
  684. }
  685. }
  686. return true;
  687. } elseif ($file instanceof File) {
  688. return $file->checkExt($rule);
  689. } else {
  690. return false;
  691. }
  692. }
  693. /**
  694. * 验证上传文件类型
  695. * @access protected
  696. * @param mixed $file 上传文件
  697. * @param mixed $rule 验证规则
  698. * @return bool
  699. */
  700. protected function fileMime($file, $rule)
  701. {
  702. if (is_array($file)) {
  703. foreach ($file as $item) {
  704. if (!($item instanceof File) || !$item->checkMime($rule)) {
  705. return false;
  706. }
  707. }
  708. return true;
  709. } elseif ($file instanceof File) {
  710. return $file->checkMime($rule);
  711. } else {
  712. return false;
  713. }
  714. }
  715. /**
  716. * 验证上传文件大小
  717. * @access protected
  718. * @param mixed $file 上传文件
  719. * @param mixed $rule 验证规则
  720. * @return bool
  721. */
  722. protected function fileSize($file, $rule)
  723. {
  724. if (is_array($file)) {
  725. foreach ($file as $item) {
  726. if (!($item instanceof File) || !$item->checkSize($rule)) {
  727. return false;
  728. }
  729. }
  730. return true;
  731. } elseif ($file instanceof File) {
  732. return $file->checkSize($rule);
  733. } else {
  734. return false;
  735. }
  736. }
  737. /**
  738. * 验证图片的宽高及类型
  739. * @access protected
  740. * @param mixed $file 上传文件
  741. * @param mixed $rule 验证规则
  742. * @return bool
  743. */
  744. protected function image($file, $rule)
  745. {
  746. if (!($file instanceof File)) {
  747. return false;
  748. }
  749. if ($rule) {
  750. $rule = explode(',', $rule);
  751. list($width, $height, $type) = getimagesize($file->getRealPath());
  752. if (isset($rule[2])) {
  753. $imageType = strtolower($rule[2]);
  754. if ('jpeg' == $imageType) {
  755. $imageType = 'jpg';
  756. }
  757. if (image_type_to_extension($type, false) != $imageType) {
  758. return false;
  759. }
  760. }
  761. list($w, $h) = $rule;
  762. return $w == $width && $h == $height;
  763. } else {
  764. return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
  765. }
  766. }
  767. /**
  768. * 验证请求类型
  769. * @access protected
  770. * @param mixed $value 字段值
  771. * @param mixed $rule 验证规则
  772. * @return bool
  773. */
  774. protected function method($value, $rule)
  775. {
  776. $method = Request::instance()->method();
  777. return strtoupper($rule) == $method;
  778. }
  779. /**
  780. * 验证时间和日期是否符合指定格式
  781. * @access protected
  782. * @param mixed $value 字段值
  783. * @param mixed $rule 验证规则
  784. * @return bool
  785. */
  786. protected function dateFormat($value, $rule)
  787. {
  788. $info = date_parse_from_format($rule, $value);
  789. return 0 == $info['warning_count'] && 0 == $info['error_count'];
  790. }
  791. /**
  792. * 验证是否唯一
  793. * @access protected
  794. * @param mixed $value 字段值
  795. * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名
  796. * @param array $data 数据
  797. * @param string $field 验证字段名
  798. * @return bool
  799. */
  800. protected function unique($value, $rule, $data, $field)
  801. {
  802. if (is_string($rule)) {
  803. $rule = explode(',', $rule);
  804. }
  805. if (false !== strpos($rule[0], '\\')) {
  806. // 指定模型类
  807. $db = new $rule[0];
  808. } else {
  809. try {
  810. $db = Loader::model($rule[0]);
  811. } catch (ClassNotFoundException $e) {
  812. $db = Db::name($rule[0]);
  813. }
  814. }
  815. $key = isset($rule[1]) ? $rule[1] : $field;
  816. if (strpos($key, '^')) {
  817. // 支持多个字段验证
  818. $fields = explode('^', $key);
  819. foreach ($fields as $key) {
  820. $map[$key] = $data[$key];
  821. }
  822. } elseif (strpos($key, '=')) {
  823. parse_str($key, $map);
  824. } else {
  825. $map[$key] = $data[$field];
  826. }
  827. $pk = isset($rule[3]) ? $rule[3] : $db->getPk();
  828. if (is_string($pk)) {
  829. if (isset($rule[2])) {
  830. $map[$pk] = ['neq', $rule[2]];
  831. } elseif (isset($data[$pk])) {
  832. $map[$pk] = ['neq', $data[$pk]];
  833. }
  834. }
  835. if ($db->where($map)->field($pk)->find()) {
  836. return false;
  837. }
  838. return true;
  839. }
  840. /**
  841. * 使用行为类验证
  842. * @access protected
  843. * @param mixed $value 字段值
  844. * @param mixed $rule 验证规则
  845. * @param array $data 数据
  846. * @return mixed
  847. */
  848. protected function behavior($value, $rule, $data)
  849. {
  850. return Hook::exec($rule, '', $data);
  851. }
  852. /**
  853. * 使用filter_var方式验证
  854. * @access protected
  855. * @param mixed $value 字段值
  856. * @param mixed $rule 验证规则
  857. * @return bool
  858. */
  859. protected function filter($value, $rule)
  860. {
  861. if (is_string($rule) && strpos($rule, ',')) {
  862. list($rule, $param) = explode(',', $rule);
  863. } elseif (is_array($rule)) {
  864. $param = isset($rule[1]) ? $rule[1] : null;
  865. $rule = $rule[0];
  866. } else {
  867. $param = null;
  868. }
  869. return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
  870. }
  871. /**
  872. * 验证某个字段等于某个值的时候必须
  873. * @access protected
  874. * @param mixed $value 字段值
  875. * @param mixed $rule 验证规则
  876. * @param array $data 数据
  877. * @return bool
  878. */
  879. protected function requireIf($value, $rule, $data)
  880. {
  881. list($field, $val) = explode(',', $rule);
  882. if ($this->getDataValue($data, $field) == $val) {
  883. return !empty($value) || '0' == $value;
  884. } else {
  885. return true;
  886. }
  887. }
  888. /**
  889. * 通过回调方法验证某个字段是否必须
  890. * @access protected
  891. * @param mixed $value 字段值
  892. * @param mixed $rule 验证规则
  893. * @param array $data 数据
  894. * @return bool
  895. */
  896. protected function requireCallback($value, $rule, $data)
  897. {
  898. $result = call_user_func_array($rule, [$value, $data]);
  899. if ($result) {
  900. return !empty($value) || '0' == $value;
  901. } else {
  902. return true;
  903. }
  904. }
  905. /**
  906. * 验证某个字段有值的情况下必须
  907. * @access protected
  908. * @param mixed $value 字段值
  909. * @param mixed $rule 验证规则
  910. * @param array $data 数据
  911. * @return bool
  912. */
  913. protected function requireWith($value, $rule, $data)
  914. {
  915. $val = $this->getDataValue($data, $rule);
  916. if (!empty($val)) {
  917. return !empty($value) || '0' == $value;
  918. } else {
  919. return true;
  920. }
  921. }
  922. /**
  923. * 验证是否在范围内
  924. * @access protected
  925. * @param mixed $value 字段值
  926. * @param mixed $rule 验证规则
  927. * @return bool
  928. */
  929. protected function in($value, $rule)
  930. {
  931. return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  932. }
  933. /**
  934. * 验证是否不在某个范围
  935. * @access protected
  936. * @param mixed $value 字段值
  937. * @param mixed $rule 验证规则
  938. * @return bool
  939. */
  940. protected function notIn($value, $rule)
  941. {
  942. return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  943. }
  944. /**
  945. * between验证数据
  946. * @access protected
  947. * @param mixed $value 字段值
  948. * @param mixed $rule 验证规则
  949. * @return bool
  950. */
  951. protected function between($value, $rule)
  952. {
  953. if (is_string($rule)) {
  954. $rule = explode(',', $rule);
  955. }
  956. list($min, $max) = $rule;
  957. return $value >= $min && $value <= $max;
  958. }
  959. /**
  960. * 使用notbetween验证数据
  961. * @access protected
  962. * @param mixed $value 字段值
  963. * @param mixed $rule 验证规则
  964. * @return bool
  965. */
  966. protected function notBetween($value, $rule)
  967. {
  968. if (is_string($rule)) {
  969. $rule = explode(',', $rule);
  970. }
  971. list($min, $max) = $rule;
  972. return $value < $min || $value > $max;
  973. }
  974. /**
  975. * 验证数据长度
  976. * @access protected
  977. * @param mixed $value 字段值
  978. * @param mixed $rule 验证规则
  979. * @return bool
  980. */
  981. protected function length($value, $rule)
  982. {
  983. if (is_array($value)) {
  984. $length = count($value);
  985. } elseif ($value instanceof File) {
  986. $length = $value->getSize();
  987. } else {
  988. $length = mb_strlen((string) $value);
  989. }
  990. if (strpos($rule, ',')) {
  991. // 长度区间
  992. list($min, $max) = explode(',', $rule);
  993. return $length >= $min && $length <= $max;
  994. } else {
  995. // 指定长度
  996. return $length == $rule;
  997. }
  998. }
  999. /**
  1000. * 验证数据最大长度
  1001. * @access protected
  1002. * @param mixed $value 字段值
  1003. * @param mixed $rule 验证规则
  1004. * @return bool
  1005. */
  1006. protected function max($value, $rule)
  1007. {
  1008. if (is_array($value)) {
  1009. $length = count($value);
  1010. } elseif ($value instanceof File) {
  1011. $length = $value->getSize();
  1012. } else {
  1013. $length = mb_strlen((string) $value);
  1014. }
  1015. return $length <= $rule;
  1016. }
  1017. /**
  1018. * 验证数据最小长度
  1019. * @access protected
  1020. * @param mixed $value 字段值
  1021. * @param mixed $rule 验证规则
  1022. * @return bool
  1023. */
  1024. protected function min($value, $rule)
  1025. {
  1026. if (is_array($value)) {
  1027. $length = count($value);
  1028. } elseif ($value instanceof File) {
  1029. $length = $value->getSize();
  1030. } else {
  1031. $length = mb_strlen((string) $value);
  1032. }
  1033. return $length >= $rule;
  1034. }
  1035. /**
  1036. * 验证日期
  1037. * @access protected
  1038. * @param mixed $value 字段值
  1039. * @param mixed $rule 验证规则
  1040. * @return bool
  1041. */
  1042. protected function after($value, $rule)
  1043. {
  1044. return strtotime($value) >= strtotime($rule);
  1045. }
  1046. /**
  1047. * 验证日期
  1048. * @access protected
  1049. * @param mixed $value 字段值
  1050. * @param mixed $rule 验证规则
  1051. * @return bool
  1052. */
  1053. protected function before($value, $rule)
  1054. {
  1055. return strtotime($value) <= strtotime($rule);
  1056. }
  1057. /**
  1058. * 验证有效期
  1059. * @access protected
  1060. * @param mixed $value 字段值
  1061. * @param mixed $rule 验证规则
  1062. * @return bool
  1063. */
  1064. protected function expire($value, $rule)
  1065. {
  1066. if (is_string($rule)) {
  1067. $rule = explode(',', $rule);
  1068. }
  1069. list($start, $end) = $rule;
  1070. if (!is_numeric($start)) {
  1071. $start = strtotime($start);
  1072. }
  1073. if (!is_numeric($end)) {
  1074. $end = strtotime($end);
  1075. }
  1076. return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
  1077. }
  1078. /**
  1079. * 验证IP许可
  1080. * @access protected
  1081. * @param string $value 字段值
  1082. * @param mixed $rule 验证规则
  1083. * @return mixed
  1084. */
  1085. protected function allowIp($value, $rule)
  1086. {
  1087. return in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1088. }
  1089. /**
  1090. * 验证IP禁用
  1091. * @access protected
  1092. * @param string $value 字段值
  1093. * @param mixed $rule 验证规则
  1094. * @return mixed
  1095. */
  1096. protected function denyIp($value, $rule)
  1097. {
  1098. return !in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1099. }
  1100. /**
  1101. * 使用正则验证数据
  1102. * @access protected
  1103. * @param mixed $value 字段值
  1104. * @param mixed $rule 验证规则 正则规则或者预定义正则名
  1105. * @return mixed
  1106. */
  1107. protected function regex($value, $rule)
  1108. {
  1109. if (isset($this->regex[$rule])) {
  1110. $rule = $this->regex[$rule];
  1111. }
  1112. if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
  1113. // 不是正则表达式则两端补上/
  1114. $rule = '/^' . $rule . '$/';
  1115. }
  1116. return 1 === preg_match($rule, (string) $value);
  1117. }
  1118. /**
  1119. * 验证表单令牌
  1120. * @access protected
  1121. * @param mixed $value 字段值
  1122. * @param mixed $rule 验证规则
  1123. * @param array $data 数据
  1124. * @return bool
  1125. */
  1126. protected function token($value, $rule, $data)
  1127. {
  1128. $rule = !empty($rule) ? $rule : '__token__';
  1129. if (!isset($data[$rule]) || !Session::has($rule)) {
  1130. // 令牌数据无效
  1131. return false;
  1132. }
  1133. // 令牌验证
  1134. if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) {
  1135. // 防止重复提交
  1136. Session::delete($rule); // 验证完成销毁session
  1137. return true;
  1138. }
  1139. // 开启TOKEN重置
  1140. Session::delete($rule);
  1141. return false;
  1142. }
  1143. // 获取错误信息
  1144. public function getError()
  1145. {
  1146. return $this->error;
  1147. }
  1148. /**
  1149. * 获取数据值
  1150. * @access protected
  1151. * @param array $data 数据
  1152. * @param string $key 数据标识 支持二维
  1153. * @return mixed
  1154. */
  1155. protected function getDataValue($data, $key)
  1156. {
  1157. if (is_numeric($key)) {
  1158. $value = $key;
  1159. } elseif (strpos($key, '.')) {
  1160. // 支持二维数组验证
  1161. list($name1, $name2) = explode('.', $key);
  1162. $value = isset($data[$name1][$name2]) ? $data[$name1][$name2] : null;
  1163. } else {
  1164. $value = isset($data[$key]) ? $data[$key] : null;
  1165. }
  1166. return $value;
  1167. }
  1168. /**
  1169. * 获取验证规则的错误提示信息
  1170. * @access protected
  1171. * @param string $attribute 字段英文名
  1172. * @param string $title 字段描述名
  1173. * @param string $type 验证规则名称
  1174. * @param mixed $rule 验证规则数据
  1175. * @return string
  1176. */
  1177. protected function getRuleMsg($attribute, $title, $type, $rule)
  1178. {
  1179. if (isset($this->message[$attribute . '.' . $type])) {
  1180. $msg = $this->message[$attribute . '.' . $type];
  1181. } elseif (isset($this->message[$attribute][$type])) {
  1182. $msg = $this->message[$attribute][$type];
  1183. } elseif (isset($this->message[$attribute])) {
  1184. $msg = $this->message[$attribute];
  1185. } elseif (isset(self::$typeMsg[$type])) {
  1186. $msg = self::$typeMsg[$type];
  1187. } elseif (0 === strpos($type, 'require')) {
  1188. $msg = self::$typeMsg['require'];
  1189. } else {
  1190. $msg = $title . Lang::get('not conform to the rules');
  1191. }
  1192. if (is_string($msg) && 0 === strpos($msg, '{%')) {
  1193. $msg = Lang::get(substr($msg, 2, -1));
  1194. } elseif (Lang::has($msg)) {
  1195. $msg = Lang::get($msg);
  1196. }
  1197. if (is_string($msg) && is_scalar($rule) && false !== strpos($msg, ':')) {
  1198. // 变量替换
  1199. if (is_string($rule) && strpos($rule, ',')) {
  1200. $array = array_pad(explode(',', $rule), 3, '');
  1201. } else {
  1202. $array = array_pad([], 3, '');
  1203. }
  1204. $msg = str_replace(
  1205. [':attribute', ':rule', ':1', ':2', ':3'],
  1206. [$title, (string) $rule, $array[0], $array[1], $array[2]],
  1207. $msg);
  1208. }
  1209. return $msg;
  1210. }
  1211. /**
  1212. * 获取数据验证的场景
  1213. * @access protected
  1214. * @param string $scene 验证场景
  1215. * @return array
  1216. */
  1217. protected function getScene($scene = '')
  1218. {
  1219. if (empty($scene)) {
  1220. // 读取指定场景
  1221. $scene = $this->currentScene;
  1222. }
  1223. if (!empty($scene) && isset($this->scene[$scene])) {
  1224. // 如果设置了验证适用场景
  1225. $scene = $this->scene[$scene];
  1226. if (is_string($scene)) {
  1227. $scene = explode(',', $scene);
  1228. }
  1229. } else {
  1230. $scene = [];
  1231. }
  1232. return $scene;
  1233. }
  1234. public static function __callStatic($method, $params)
  1235. {
  1236. $class = self::make();
  1237. if (method_exists($class, $method)) {
  1238. return call_user_func_array([$class, $method], $params);
  1239. } else {
  1240. throw new \BadMethodCallException('method not exists:' . __CLASS__ . '->' . $method);
  1241. }
  1242. }
  1243. }