Validate.php 39 KB

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