Validate.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2017 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 string $field 字段名
  316. * @param mixed $value 字段值
  317. * @param mixed $rules 验证规则
  318. * @param array $data 数据
  319. * @param string $title 字段描述
  320. * @param array $msg 提示信息
  321. * @return mixed
  322. */
  323. protected function checkItem($field, $value, $rules, $data, $title = '', $msg = [])
  324. {
  325. // 支持多规则验证 require|in:a,b,c|... 或者 ['require','in'=>'a,b,c',...]
  326. if (is_string($rules)) {
  327. $rules = explode('|', $rules);
  328. }
  329. $i = 0;
  330. foreach ($rules as $key => $rule) {
  331. if ($rule instanceof \Closure) {
  332. $result = call_user_func_array($rule, [$value, $data]);
  333. $info = is_numeric($key) ? '' : $key;
  334. } else {
  335. // 判断验证类型
  336. if (is_numeric($key)) {
  337. if (strpos($rule, ':')) {
  338. list($type, $rule) = explode(':', $rule, 2);
  339. if (isset($this->alias[$type])) {
  340. // 判断别名
  341. $type = $this->alias[$type];
  342. }
  343. $info = $type;
  344. } elseif (method_exists($this, $rule)) {
  345. $type = $rule;
  346. $info = $rule;
  347. $rule = '';
  348. } else {
  349. $type = 'is';
  350. $info = $rule;
  351. }
  352. } else {
  353. $info = $type = $key;
  354. }
  355. // 如果不是require 有数据才会行验证
  356. if (0 === strpos($info, 'require') || (!is_null($value) && '' !== $value)) {
  357. // 验证类型
  358. $callback = isset(self::$type[$type]) ? self::$type[$type] : [$this, $type];
  359. // 验证数据
  360. $result = call_user_func_array($callback, [$value, $rule, $data, $field, $title]);
  361. } else {
  362. $result = true;
  363. }
  364. }
  365. if (false === $result) {
  366. // 验证失败 返回错误信息
  367. if (isset($msg[$i])) {
  368. $message = $msg[$i];
  369. if (is_string($message) && strpos($message, '{%') === 0) {
  370. $message = Lang::get(substr($message, 2, -1));
  371. }
  372. } else {
  373. $message = $this->getRuleMsg($field, $title, $info, $rule);
  374. }
  375. return $message;
  376. } elseif (true !== $result) {
  377. // 返回自定义错误信息
  378. if (is_string($result) && false !== strpos($result, ':')) {
  379. $result = str_replace([':attribute', ':rule'], [$title, (string) $rule], $result);
  380. }
  381. return $result;
  382. }
  383. $i++;
  384. }
  385. return $result;
  386. }
  387. /**
  388. * 验证是否和某个字段的值一致
  389. * @access protected
  390. * @param mixed $value 字段值
  391. * @param mixed $rule 验证规则
  392. * @param array $data 数据
  393. * @param string $field 字段名
  394. * @return bool
  395. */
  396. protected function confirm($value, $rule, $data, $field = '')
  397. {
  398. if ('' == $rule) {
  399. if (strpos($field, '_confirm')) {
  400. $rule = strstr($field, '_confirm', true);
  401. } else {
  402. $rule = $field . '_confirm';
  403. }
  404. }
  405. return $this->getDataValue($data, $rule) === $value;
  406. }
  407. /**
  408. * 验证是否和某个字段的值是否不同
  409. * @access protected
  410. * @param mixed $value 字段值
  411. * @param mixed $rule 验证规则
  412. * @param array $data 数据
  413. * @return bool
  414. */
  415. protected function different($value, $rule, $data)
  416. {
  417. return $this->getDataValue($data, $rule) != $value;
  418. }
  419. /**
  420. * 验证是否大于等于某个值
  421. * @access protected
  422. * @param mixed $value 字段值
  423. * @param mixed $rule 验证规则
  424. * @param array $data 数据
  425. * @return bool
  426. */
  427. protected function egt($value, $rule, $data)
  428. {
  429. $val = $this->getDataValue($data, $rule);
  430. return !is_null($val) && $value >= $val;
  431. }
  432. /**
  433. * 验证是否大于某个值
  434. * @access protected
  435. * @param mixed $value 字段值
  436. * @param mixed $rule 验证规则
  437. * @param array $data 数据
  438. * @return bool
  439. */
  440. protected function gt($value, $rule, $data)
  441. {
  442. $val = $this->getDataValue($data, $rule);
  443. return !is_null($val) && $value > $val;
  444. }
  445. /**
  446. * 验证是否小于等于某个值
  447. * @access protected
  448. * @param mixed $value 字段值
  449. * @param mixed $rule 验证规则
  450. * @param array $data 数据
  451. * @return bool
  452. */
  453. protected function elt($value, $rule, $data)
  454. {
  455. $val = $this->getDataValue($data, $rule);
  456. return !is_null($val) && $value <= $val;
  457. }
  458. /**
  459. * 验证是否小于某个值
  460. * @access protected
  461. * @param mixed $value 字段值
  462. * @param mixed $rule 验证规则
  463. * @param array $data 数据
  464. * @return bool
  465. */
  466. protected function lt($value, $rule, $data)
  467. {
  468. $val = $this->getDataValue($data, $rule);
  469. return !is_null($val) && $value < $val;
  470. }
  471. /**
  472. * 验证是否等于某个值
  473. * @access protected
  474. * @param mixed $value 字段值
  475. * @param mixed $rule 验证规则
  476. * @return bool
  477. */
  478. protected function eq($value, $rule)
  479. {
  480. return $value == $rule;
  481. }
  482. /**
  483. * 验证字段值是否为有效格式
  484. * @access protected
  485. * @param mixed $value 字段值
  486. * @param string $rule 验证规则
  487. * @param array $data 验证数据
  488. * @return bool
  489. */
  490. protected function is($value, $rule, $data = [])
  491. {
  492. switch ($rule) {
  493. case 'require':
  494. // 必须
  495. $result = !empty($value) || '0' == $value;
  496. break;
  497. case 'accepted':
  498. // 接受
  499. $result = in_array($value, ['1', 'on', 'yes']);
  500. break;
  501. case 'date':
  502. // 是否是一个有效日期
  503. $result = false !== strtotime($value);
  504. break;
  505. case 'alpha':
  506. // 只允许字母
  507. $result = $this->regex($value, '/^[A-Za-z]+$/');
  508. break;
  509. case 'alphaNum':
  510. // 只允许字母和数字
  511. $result = $this->regex($value, '/^[A-Za-z0-9]+$/');
  512. break;
  513. case 'alphaDash':
  514. // 只允许字母、数字和下划线 破折号
  515. $result = $this->regex($value, '/^[A-Za-z0-9\-\_]+$/');
  516. break;
  517. case 'chs':
  518. // 只允许汉字
  519. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}]+$/u');
  520. break;
  521. case 'chsAlpha':
  522. // 只允许汉字、字母
  523. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z]+$/u');
  524. break;
  525. case 'chsAlphaNum':
  526. // 只允许汉字、字母和数字
  527. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9]+$/u');
  528. break;
  529. case 'chsDash':
  530. // 只允许汉字、字母、数字和下划线_及破折号-
  531. $result = $this->regex($value, '/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$/u');
  532. break;
  533. case 'activeUrl':
  534. // 是否为有效的网址
  535. $result = checkdnsrr($value);
  536. break;
  537. case 'ip':
  538. // 是否为IP地址
  539. $result = $this->filter($value, [FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6]);
  540. break;
  541. case 'url':
  542. // 是否为一个URL地址
  543. $result = $this->filter($value, FILTER_VALIDATE_URL);
  544. break;
  545. case 'float':
  546. // 是否为float
  547. $result = $this->filter($value, FILTER_VALIDATE_FLOAT);
  548. break;
  549. case 'number':
  550. $result = is_numeric($value);
  551. break;
  552. case 'integer':
  553. // 是否为整型
  554. $result = $this->filter($value, FILTER_VALIDATE_INT);
  555. break;
  556. case 'email':
  557. // 是否为邮箱地址
  558. $result = $this->filter($value, FILTER_VALIDATE_EMAIL);
  559. break;
  560. case 'boolean':
  561. // 是否为布尔值
  562. $result = in_array($value, [true, false, 0, 1, '0', '1'], true);
  563. break;
  564. case 'array':
  565. // 是否为数组
  566. $result = is_array($value);
  567. break;
  568. case 'file':
  569. $result = $value instanceof File;
  570. break;
  571. case 'image':
  572. $result = $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]);
  573. break;
  574. case 'token':
  575. $result = $this->token($value, '__token__', $data);
  576. break;
  577. default:
  578. if (isset(self::$type[$rule])) {
  579. // 注册的验证规则
  580. $result = call_user_func_array(self::$type[$rule], [$value]);
  581. } else {
  582. // 正则验证
  583. $result = $this->regex($value, $rule);
  584. }
  585. }
  586. return $result;
  587. }
  588. // 判断图像类型
  589. protected function getImageType($image)
  590. {
  591. if (function_exists('exif_imagetype')) {
  592. return exif_imagetype($image);
  593. } else {
  594. try {
  595. $info = getimagesize($image);
  596. return $info ? $info[2] : false;
  597. } catch (\Exception $e) {
  598. return false;
  599. }
  600. }
  601. }
  602. /**
  603. * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
  604. * @access protected
  605. * @param mixed $value 字段值
  606. * @param mixed $rule 验证规则
  607. * @return bool
  608. */
  609. protected function activeUrl($value, $rule)
  610. {
  611. if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
  612. $rule = 'MX';
  613. }
  614. return checkdnsrr($value, $rule);
  615. }
  616. /**
  617. * 验证是否有效IP
  618. * @access protected
  619. * @param mixed $value 字段值
  620. * @param mixed $rule 验证规则 ipv4 ipv6
  621. * @return bool
  622. */
  623. protected function ip($value, $rule)
  624. {
  625. if (!in_array($rule, ['ipv4', 'ipv6'])) {
  626. $rule = 'ipv4';
  627. }
  628. return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]);
  629. }
  630. /**
  631. * 验证上传文件后缀
  632. * @access protected
  633. * @param mixed $file 上传文件
  634. * @param mixed $rule 验证规则
  635. * @return bool
  636. */
  637. protected function fileExt($file, $rule)
  638. {
  639. if (!($file instanceof File)) {
  640. return false;
  641. }
  642. if (is_string($rule)) {
  643. $rule = explode(',', $rule);
  644. }
  645. if (is_array($file)) {
  646. foreach ($file as $item) {
  647. if (!$item->checkExt($rule)) {
  648. return false;
  649. }
  650. }
  651. return true;
  652. } else {
  653. return $file->checkExt($rule);
  654. }
  655. }
  656. /**
  657. * 验证上传文件类型
  658. * @access protected
  659. * @param mixed $file 上传文件
  660. * @param mixed $rule 验证规则
  661. * @return bool
  662. */
  663. protected function fileMime($file, $rule)
  664. {
  665. if (!($file instanceof File)) {
  666. return false;
  667. }
  668. if (is_string($rule)) {
  669. $rule = explode(',', $rule);
  670. }
  671. if (is_array($file)) {
  672. foreach ($file as $item) {
  673. if (!$item->checkMime($rule)) {
  674. return false;
  675. }
  676. }
  677. return true;
  678. } else {
  679. return $file->checkMime($rule);
  680. }
  681. }
  682. /**
  683. * 验证上传文件大小
  684. * @access protected
  685. * @param mixed $file 上传文件
  686. * @param mixed $rule 验证规则
  687. * @return bool
  688. */
  689. protected function fileSize($file, $rule)
  690. {
  691. if (!($file instanceof File)) {
  692. return false;
  693. }
  694. if (is_array($file)) {
  695. foreach ($file as $item) {
  696. if (!$item->checkSize($rule)) {
  697. return false;
  698. }
  699. }
  700. return true;
  701. } else {
  702. return $file->checkSize($rule);
  703. }
  704. }
  705. /**
  706. * 验证图片的宽高及类型
  707. * @access protected
  708. * @param mixed $file 上传文件
  709. * @param mixed $rule 验证规则
  710. * @return bool
  711. */
  712. protected function image($file, $rule)
  713. {
  714. if (!($file instanceof File)) {
  715. return false;
  716. }
  717. if ($rule) {
  718. $rule = explode(',', $rule);
  719. list($width, $height, $type) = getimagesize($file->getRealPath());
  720. if (isset($rule[2])) {
  721. $imageType = strtolower($rule[2]);
  722. if ('jpeg' == $imageType) {
  723. $imageType = 'jpg';
  724. }
  725. if (image_type_to_extension($type, false) != $imageType) {
  726. return false;
  727. }
  728. }
  729. list($w, $h) = $rule;
  730. return $w == $width && $h == $height;
  731. } else {
  732. return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
  733. }
  734. }
  735. /**
  736. * 验证请求类型
  737. * @access protected
  738. * @param mixed $value 字段值
  739. * @param mixed $rule 验证规则
  740. * @return bool
  741. */
  742. protected function method($value, $rule)
  743. {
  744. $method = Request::instance()->method();
  745. return strtoupper($rule) == $method;
  746. }
  747. /**
  748. * 验证时间和日期是否符合指定格式
  749. * @access protected
  750. * @param mixed $value 字段值
  751. * @param mixed $rule 验证规则
  752. * @return bool
  753. */
  754. protected function dateFormat($value, $rule)
  755. {
  756. $info = date_parse_from_format($rule, $value);
  757. return 0 == $info['warning_count'] && 0 == $info['error_count'];
  758. }
  759. /**
  760. * 验证是否唯一
  761. * @access protected
  762. * @param mixed $value 字段值
  763. * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名
  764. * @param array $data 数据
  765. * @param string $field 验证字段名
  766. * @return bool
  767. */
  768. protected function unique($value, $rule, $data, $field)
  769. {
  770. if (is_string($rule)) {
  771. $rule = explode(',', $rule);
  772. }
  773. if (false !== strpos($rule[0], '\\')) {
  774. // 指定模型类
  775. $db = new $rule[0];
  776. } else {
  777. try {
  778. $db = Loader::model($rule[0]);
  779. } catch (ClassNotFoundException $e) {
  780. $db = Db::name($rule[0]);
  781. }
  782. }
  783. $key = isset($rule[1]) ? $rule[1] : $field;
  784. if (strpos($key, '^')) {
  785. // 支持多个字段验证
  786. $fields = explode('^', $key);
  787. foreach ($fields as $key) {
  788. $map[$key] = $data[$key];
  789. }
  790. } elseif (strpos($key, '=')) {
  791. parse_str($key, $map);
  792. } else {
  793. $map[$key] = $data[$field];
  794. }
  795. $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk());
  796. if (isset($rule[2])) {
  797. $map[$pk] = ['neq', $rule[2]];
  798. } elseif (isset($data[$pk])) {
  799. $map[$pk] = ['neq', $data[$pk]];
  800. }
  801. if ($db->where($map)->field($pk)->find()) {
  802. return false;
  803. }
  804. return true;
  805. }
  806. /**
  807. * 使用行为类验证
  808. * @access protected
  809. * @param mixed $value 字段值
  810. * @param mixed $rule 验证规则
  811. * @param array $data 数据
  812. * @return mixed
  813. */
  814. protected function behavior($value, $rule, $data)
  815. {
  816. return Hook::exec($rule, '', $data);
  817. }
  818. /**
  819. * 使用filter_var方式验证
  820. * @access protected
  821. * @param mixed $value 字段值
  822. * @param mixed $rule 验证规则
  823. * @return bool
  824. */
  825. protected function filter($value, $rule)
  826. {
  827. if (is_string($rule) && strpos($rule, ',')) {
  828. list($rule, $param) = explode(',', $rule);
  829. } elseif (is_array($rule)) {
  830. $param = isset($rule[1]) ? $rule[1] : null;
  831. $rule = $rule[0];
  832. } else {
  833. $param = null;
  834. }
  835. return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
  836. }
  837. /**
  838. * 验证某个字段等于某个值的时候必须
  839. * @access protected
  840. * @param mixed $value 字段值
  841. * @param mixed $rule 验证规则
  842. * @param array $data 数据
  843. * @return bool
  844. */
  845. protected function requireIf($value, $rule, $data)
  846. {
  847. list($field, $val) = explode(',', $rule);
  848. if ($this->getDataValue($data, $field) == $val) {
  849. return !empty($value) || '0' == $value;
  850. } else {
  851. return true;
  852. }
  853. }
  854. /**
  855. * 通过回调方法验证某个字段是否必须
  856. * @access protected
  857. * @param mixed $value 字段值
  858. * @param mixed $rule 验证规则
  859. * @param array $data 数据
  860. * @return bool
  861. */
  862. protected function requireCallback($value, $rule, $data)
  863. {
  864. $result = call_user_func_array($rule, [$value, $data]);
  865. if ($result) {
  866. return !empty($value) || '0' == $value;
  867. } else {
  868. return true;
  869. }
  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 requireWith($value, $rule, $data)
  880. {
  881. $val = $this->getDataValue($data, $rule);
  882. if (!empty($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. * @return bool
  894. */
  895. protected function in($value, $rule)
  896. {
  897. return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  898. }
  899. /**
  900. * 验证是否不在某个范围
  901. * @access protected
  902. * @param mixed $value 字段值
  903. * @param mixed $rule 验证规则
  904. * @return bool
  905. */
  906. protected function notIn($value, $rule)
  907. {
  908. return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  909. }
  910. /**
  911. * between验证数据
  912. * @access protected
  913. * @param mixed $value 字段值
  914. * @param mixed $rule 验证规则
  915. * @return bool
  916. */
  917. protected function between($value, $rule)
  918. {
  919. if (is_string($rule)) {
  920. $rule = explode(',', $rule);
  921. }
  922. list($min, $max) = $rule;
  923. return $value >= $min && $value <= $max;
  924. }
  925. /**
  926. * 使用notbetween验证数据
  927. * @access protected
  928. * @param mixed $value 字段值
  929. * @param mixed $rule 验证规则
  930. * @return bool
  931. */
  932. protected function notBetween($value, $rule)
  933. {
  934. if (is_string($rule)) {
  935. $rule = explode(',', $rule);
  936. }
  937. list($min, $max) = $rule;
  938. return $value < $min || $value > $max;
  939. }
  940. /**
  941. * 验证数据长度
  942. * @access protected
  943. * @param mixed $value 字段值
  944. * @param mixed $rule 验证规则
  945. * @return bool
  946. */
  947. protected function length($value, $rule)
  948. {
  949. if (is_array($value)) {
  950. $length = count($value);
  951. } elseif ($value instanceof File) {
  952. $length = $value->getSize();
  953. } else {
  954. $length = mb_strlen((string) $value);
  955. }
  956. if (strpos($rule, ',')) {
  957. // 长度区间
  958. list($min, $max) = explode(',', $rule);
  959. return $length >= $min && $length <= $max;
  960. } else {
  961. // 指定长度
  962. return $length == $rule;
  963. }
  964. }
  965. /**
  966. * 验证数据最大长度
  967. * @access protected
  968. * @param mixed $value 字段值
  969. * @param mixed $rule 验证规则
  970. * @return bool
  971. */
  972. protected function max($value, $rule)
  973. {
  974. if (is_array($value)) {
  975. $length = count($value);
  976. } elseif ($value instanceof File) {
  977. $length = $value->getSize();
  978. } else {
  979. $length = mb_strlen((string) $value);
  980. }
  981. return $length <= $rule;
  982. }
  983. /**
  984. * 验证数据最小长度
  985. * @access protected
  986. * @param mixed $value 字段值
  987. * @param mixed $rule 验证规则
  988. * @return bool
  989. */
  990. protected function min($value, $rule)
  991. {
  992. if (is_array($value)) {
  993. $length = count($value);
  994. } elseif ($value instanceof File) {
  995. $length = $value->getSize();
  996. } else {
  997. $length = mb_strlen((string) $value);
  998. }
  999. return $length >= $rule;
  1000. }
  1001. /**
  1002. * 验证日期
  1003. * @access protected
  1004. * @param mixed $value 字段值
  1005. * @param mixed $rule 验证规则
  1006. * @return bool
  1007. */
  1008. protected function after($value, $rule)
  1009. {
  1010. return strtotime($value) >= strtotime($rule);
  1011. }
  1012. /**
  1013. * 验证日期
  1014. * @access protected
  1015. * @param mixed $value 字段值
  1016. * @param mixed $rule 验证规则
  1017. * @return bool
  1018. */
  1019. protected function before($value, $rule)
  1020. {
  1021. return strtotime($value) <= strtotime($rule);
  1022. }
  1023. /**
  1024. * 验证有效期
  1025. * @access protected
  1026. * @param mixed $value 字段值
  1027. * @param mixed $rule 验证规则
  1028. * @return bool
  1029. */
  1030. protected function expire($value, $rule)
  1031. {
  1032. if (is_string($rule)) {
  1033. $rule = explode(',', $rule);
  1034. }
  1035. list($start, $end) = $rule;
  1036. if (!is_numeric($start)) {
  1037. $start = strtotime($start);
  1038. }
  1039. if (!is_numeric($end)) {
  1040. $end = strtotime($end);
  1041. }
  1042. return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
  1043. }
  1044. /**
  1045. * 验证IP许可
  1046. * @access protected
  1047. * @param string $value 字段值
  1048. * @param mixed $rule 验证规则
  1049. * @return mixed
  1050. */
  1051. protected function allowIp($value, $rule)
  1052. {
  1053. return in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1054. }
  1055. /**
  1056. * 验证IP禁用
  1057. * @access protected
  1058. * @param string $value 字段值
  1059. * @param mixed $rule 验证规则
  1060. * @return mixed
  1061. */
  1062. protected function denyIp($value, $rule)
  1063. {
  1064. return !in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1065. }
  1066. /**
  1067. * 使用正则验证数据
  1068. * @access protected
  1069. * @param mixed $value 字段值
  1070. * @param mixed $rule 验证规则 正则规则或者预定义正则名
  1071. * @return mixed
  1072. */
  1073. protected function regex($value, $rule)
  1074. {
  1075. if (isset($this->regex[$rule])) {
  1076. $rule = $this->regex[$rule];
  1077. }
  1078. if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
  1079. // 不是正则表达式则两端补上/
  1080. $rule = '/^' . $rule . '$/';
  1081. }
  1082. return 1 === preg_match($rule, (string) $value);
  1083. }
  1084. /**
  1085. * 验证表单令牌
  1086. * @access protected
  1087. * @param mixed $value 字段值
  1088. * @param mixed $rule 验证规则
  1089. * @param array $data 数据
  1090. * @return bool
  1091. */
  1092. protected function token($value, $rule, $data)
  1093. {
  1094. $rule = !empty($rule) ? $rule : '__token__';
  1095. if (!isset($data[$rule]) || !Session::has($rule)) {
  1096. // 令牌数据无效
  1097. return false;
  1098. }
  1099. // 令牌验证
  1100. if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) {
  1101. // 防止重复提交
  1102. Session::delete($rule); // 验证完成销毁session
  1103. return true;
  1104. }
  1105. // 开启TOKEN重置
  1106. Session::delete($rule);
  1107. return false;
  1108. }
  1109. // 获取错误信息
  1110. public function getError()
  1111. {
  1112. return $this->error;
  1113. }
  1114. /**
  1115. * 获取数据值
  1116. * @access protected
  1117. * @param array $data 数据
  1118. * @param string $key 数据标识 支持二维
  1119. * @return mixed
  1120. */
  1121. protected function getDataValue($data, $key)
  1122. {
  1123. if (is_numeric($key)) {
  1124. $value = $key;
  1125. } elseif (strpos($key, '.')) {
  1126. // 支持二维数组验证
  1127. list($name1, $name2) = explode('.', $key);
  1128. $value = isset($data[$name1][$name2]) ? $data[$name1][$name2] : null;
  1129. } else {
  1130. $value = isset($data[$key]) ? $data[$key] : null;
  1131. }
  1132. return $value;
  1133. }
  1134. /**
  1135. * 获取验证规则的错误提示信息
  1136. * @access protected
  1137. * @param string $attribute 字段英文名
  1138. * @param string $title 字段描述名
  1139. * @param string $type 验证规则名称
  1140. * @param mixed $rule 验证规则数据
  1141. * @return string
  1142. */
  1143. protected function getRuleMsg($attribute, $title, $type, $rule)
  1144. {
  1145. if (isset($this->message[$attribute . '.' . $type])) {
  1146. $msg = $this->message[$attribute . '.' . $type];
  1147. } elseif (isset($this->message[$attribute][$type])) {
  1148. $msg = $this->message[$attribute][$type];
  1149. } elseif (isset($this->message[$attribute])) {
  1150. $msg = $this->message[$attribute];
  1151. } elseif (isset(self::$typeMsg[$type])) {
  1152. $msg = self::$typeMsg[$type];
  1153. } elseif (0 === strpos($type, 'require')) {
  1154. $msg = self::$typeMsg['require'];
  1155. } else {
  1156. $msg = $title . Lang::get('not conform to the rules');
  1157. }
  1158. if (is_string($msg) && 0 === strpos($msg, '{%')) {
  1159. $msg = Lang::get(substr($msg, 2, -1));
  1160. } elseif (Lang::has($msg)) {
  1161. $msg = Lang::get($msg);
  1162. }
  1163. if (is_string($msg) && is_scalar($rule) && false !== strpos($msg, ':')) {
  1164. // 变量替换
  1165. if (is_string($rule) && strpos($rule, ',')) {
  1166. $array = array_pad(explode(',', $rule), 3, '');
  1167. } else {
  1168. $array = array_pad([], 3, '');
  1169. }
  1170. $msg = str_replace(
  1171. [':attribute', ':rule', ':1', ':2', ':3'],
  1172. [$title, (string) $rule, $array[0], $array[1], $array[2]],
  1173. $msg);
  1174. }
  1175. return $msg;
  1176. }
  1177. /**
  1178. * 获取数据验证的场景
  1179. * @access protected
  1180. * @param string $scene 验证场景
  1181. * @return array
  1182. */
  1183. protected function getScene($scene = '')
  1184. {
  1185. if (empty($scene)) {
  1186. // 读取指定场景
  1187. $scene = $this->currentScene;
  1188. }
  1189. if (!empty($scene) && isset($this->scene[$scene])) {
  1190. // 如果设置了验证适用场景
  1191. $scene = $this->scene[$scene];
  1192. if (is_string($scene)) {
  1193. $scene = explode(',', $scene);
  1194. }
  1195. } else {
  1196. $scene = [];
  1197. }
  1198. return $scene;
  1199. }
  1200. public static function __callStatic($method, $params)
  1201. {
  1202. $class = self::make();
  1203. if (method_exists($class, $method)) {
  1204. return call_user_func_array([$class, $method], $params);
  1205. } else {
  1206. throw new \BadMethodCallException('method not exists:' . __CLASS__ . '->' . $method);
  1207. }
  1208. }
  1209. }