Validate.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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. 'integer' => ':attribute必须是整数',
  34. 'float' => ':attribute必须是浮点数',
  35. 'boolean' => ':attribute必须是布尔值',
  36. 'email' => ':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 'boolean':
  560. // 是否为布尔值
  561. $result = in_array($value, [true, false, 0, 1, '0', '1'], true);
  562. break;
  563. case 'array':
  564. // 是否为数组
  565. $result = is_array($value);
  566. break;
  567. case 'file':
  568. $result = $value instanceof File;
  569. break;
  570. case 'image':
  571. $result = $value instanceof File && in_array($this->getImageType($value->getRealPath()), [1, 2, 3, 6]);
  572. break;
  573. case 'token':
  574. $result = $this->token($value, '__token__', $data);
  575. break;
  576. default:
  577. if (isset(self::$type[$rule])) {
  578. // 注册的验证规则
  579. $result = call_user_func_array(self::$type[$rule], [$value]);
  580. } else {
  581. // 正则验证
  582. $result = $this->regex($value, $rule);
  583. }
  584. }
  585. return $result;
  586. }
  587. // 判断图像类型
  588. protected function getImageType($image)
  589. {
  590. if (function_exists('exif_imagetype')) {
  591. return exif_imagetype($image);
  592. } else {
  593. try {
  594. $info = getimagesize($image);
  595. return $info ? $info[2] : false;
  596. } catch (\Exception $e) {
  597. return false;
  598. }
  599. }
  600. }
  601. /**
  602. * 验证是否为合格的域名或者IP 支持A,MX,NS,SOA,PTR,CNAME,AAAA,A6, SRV,NAPTR,TXT 或者 ANY类型
  603. * @access protected
  604. * @param mixed $value 字段值
  605. * @param mixed $rule 验证规则
  606. * @return bool
  607. */
  608. protected function activeUrl($value, $rule)
  609. {
  610. if (!in_array($rule, ['A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV', 'NAPTR', 'TXT', 'ANY'])) {
  611. $rule = 'MX';
  612. }
  613. return checkdnsrr($value, $rule);
  614. }
  615. /**
  616. * 验证是否有效IP
  617. * @access protected
  618. * @param mixed $value 字段值
  619. * @param mixed $rule 验证规则 ipv4 ipv6
  620. * @return bool
  621. */
  622. protected function ip($value, $rule)
  623. {
  624. if (!in_array($rule, ['ipv4', 'ipv6'])) {
  625. $rule = 'ipv4';
  626. }
  627. return $this->filter($value, [FILTER_VALIDATE_IP, 'ipv6' == $rule ? FILTER_FLAG_IPV6 : FILTER_FLAG_IPV4]);
  628. }
  629. /**
  630. * 验证上传文件后缀
  631. * @access protected
  632. * @param mixed $file 上传文件
  633. * @param mixed $rule 验证规则
  634. * @return bool
  635. */
  636. protected function fileExt($file, $rule)
  637. {
  638. if (!($file instanceof File)) {
  639. return false;
  640. }
  641. if (is_string($rule)) {
  642. $rule = explode(',', $rule);
  643. }
  644. if (is_array($file)) {
  645. foreach ($file as $item) {
  646. if (!$item->checkExt($rule)) {
  647. return false;
  648. }
  649. }
  650. return true;
  651. } else {
  652. return $file->checkExt($rule);
  653. }
  654. }
  655. /**
  656. * 验证上传文件类型
  657. * @access protected
  658. * @param mixed $file 上传文件
  659. * @param mixed $rule 验证规则
  660. * @return bool
  661. */
  662. protected function fileMime($file, $rule)
  663. {
  664. if (!($file instanceof File)) {
  665. return false;
  666. }
  667. if (is_string($rule)) {
  668. $rule = explode(',', $rule);
  669. }
  670. if (is_array($file)) {
  671. foreach ($file as $item) {
  672. if (!$item->checkMime($rule)) {
  673. return false;
  674. }
  675. }
  676. return true;
  677. } else {
  678. return $file->checkMime($rule);
  679. }
  680. }
  681. /**
  682. * 验证上传文件大小
  683. * @access protected
  684. * @param mixed $file 上传文件
  685. * @param mixed $rule 验证规则
  686. * @return bool
  687. */
  688. protected function fileSize($file, $rule)
  689. {
  690. if (!($file instanceof File)) {
  691. return false;
  692. }
  693. if (is_array($file)) {
  694. foreach ($file as $item) {
  695. if (!$item->checkSize($rule)) {
  696. return false;
  697. }
  698. }
  699. return true;
  700. } else {
  701. return $file->checkSize($rule);
  702. }
  703. }
  704. /**
  705. * 验证图片的宽高及类型
  706. * @access protected
  707. * @param mixed $file 上传文件
  708. * @param mixed $rule 验证规则
  709. * @return bool
  710. */
  711. protected function image($file, $rule)
  712. {
  713. if (!($file instanceof File)) {
  714. return false;
  715. }
  716. if ($rule) {
  717. $rule = explode(',', $rule);
  718. list($width, $height, $type) = getimagesize($file->getRealPath());
  719. if (isset($rule[2])) {
  720. $imageType = strtolower($rule[2]);
  721. if ('jpeg' == $imageType) {
  722. $imageType = 'jpg';
  723. }
  724. if (image_type_to_extension($type, false) != $imageType) {
  725. return false;
  726. }
  727. }
  728. list($w, $h) = $rule;
  729. return $w == $width && $h == $height;
  730. } else {
  731. return in_array($this->getImageType($file->getRealPath()), [1, 2, 3, 6]);
  732. }
  733. }
  734. /**
  735. * 验证请求类型
  736. * @access protected
  737. * @param mixed $value 字段值
  738. * @param mixed $rule 验证规则
  739. * @return bool
  740. */
  741. protected function method($value, $rule)
  742. {
  743. $method = Request::instance()->method();
  744. return strtoupper($rule) == $method;
  745. }
  746. /**
  747. * 验证时间和日期是否符合指定格式
  748. * @access protected
  749. * @param mixed $value 字段值
  750. * @param mixed $rule 验证规则
  751. * @return bool
  752. */
  753. protected function dateFormat($value, $rule)
  754. {
  755. $info = date_parse_from_format($rule, $value);
  756. return 0 == $info['warning_count'] && 0 == $info['error_count'];
  757. }
  758. /**
  759. * 验证是否唯一
  760. * @access protected
  761. * @param mixed $value 字段值
  762. * @param mixed $rule 验证规则 格式:数据表,字段名,排除ID,主键名
  763. * @param array $data 数据
  764. * @param string $field 验证字段名
  765. * @return bool
  766. */
  767. protected function unique($value, $rule, $data, $field)
  768. {
  769. if (is_string($rule)) {
  770. $rule = explode(',', $rule);
  771. }
  772. if (false !== strpos($rule[0], '\\')) {
  773. // 指定模型类
  774. $db = new $rule[0];
  775. } else {
  776. try {
  777. $db = Loader::model($rule[0]);
  778. } catch (ClassNotFoundException $e) {
  779. $db = Db::name($rule[0]);
  780. }
  781. }
  782. $key = isset($rule[1]) ? $rule[1] : $field;
  783. if (strpos($key, '^')) {
  784. // 支持多个字段验证
  785. $fields = explode('^', $key);
  786. foreach ($fields as $key) {
  787. $map[$key] = $data[$key];
  788. }
  789. } elseif (strpos($key, '=')) {
  790. parse_str($key, $map);
  791. } else {
  792. $map[$key] = $data[$field];
  793. }
  794. $pk = strval(isset($rule[3]) ? $rule[3] : $db->getPk());
  795. if (isset($rule[2])) {
  796. $map[$pk] = ['neq', $rule[2]];
  797. } elseif (isset($data[$pk])) {
  798. $map[$pk] = ['neq', $data[$pk]];
  799. }
  800. if ($db->where($map)->field($pk)->find()) {
  801. return false;
  802. }
  803. return true;
  804. }
  805. /**
  806. * 使用行为类验证
  807. * @access protected
  808. * @param mixed $value 字段值
  809. * @param mixed $rule 验证规则
  810. * @param array $data 数据
  811. * @return mixed
  812. */
  813. protected function behavior($value, $rule, $data)
  814. {
  815. return Hook::exec($rule, '', $data);
  816. }
  817. /**
  818. * 使用filter_var方式验证
  819. * @access protected
  820. * @param mixed $value 字段值
  821. * @param mixed $rule 验证规则
  822. * @return bool
  823. */
  824. protected function filter($value, $rule)
  825. {
  826. if (is_string($rule) && strpos($rule, ',')) {
  827. list($rule, $param) = explode(',', $rule);
  828. } elseif (is_array($rule)) {
  829. $param = isset($rule[1]) ? $rule[1] : null;
  830. $rule = $rule[0];
  831. } else {
  832. $param = null;
  833. }
  834. return false !== filter_var($value, is_int($rule) ? $rule : filter_id($rule), $param);
  835. }
  836. /**
  837. * 验证某个字段等于某个值的时候必须
  838. * @access protected
  839. * @param mixed $value 字段值
  840. * @param mixed $rule 验证规则
  841. * @param array $data 数据
  842. * @return bool
  843. */
  844. protected function requireIf($value, $rule, $data)
  845. {
  846. list($field, $val) = explode(',', $rule);
  847. if ($this->getDataValue($data, $field) == $val) {
  848. return !empty($value) || '0' == $value;
  849. } else {
  850. return true;
  851. }
  852. }
  853. /**
  854. * 通过回调方法验证某个字段是否必须
  855. * @access protected
  856. * @param mixed $value 字段值
  857. * @param mixed $rule 验证规则
  858. * @param array $data 数据
  859. * @return bool
  860. */
  861. protected function requireCallback($value, $rule, $data)
  862. {
  863. $result = call_user_func_array($rule, [$value, $data]);
  864. if ($result) {
  865. return !empty($value) || '0' == $value;
  866. } else {
  867. return true;
  868. }
  869. }
  870. /**
  871. * 验证某个字段有值的情况下必须
  872. * @access protected
  873. * @param mixed $value 字段值
  874. * @param mixed $rule 验证规则
  875. * @param array $data 数据
  876. * @return bool
  877. */
  878. protected function requireWith($value, $rule, $data)
  879. {
  880. $val = $this->getDataValue($data, $rule);
  881. if (!empty($val)) {
  882. return !empty($value) || '0' == $value;
  883. } else {
  884. return true;
  885. }
  886. }
  887. /**
  888. * 验证是否在范围内
  889. * @access protected
  890. * @param mixed $value 字段值
  891. * @param mixed $rule 验证规则
  892. * @return bool
  893. */
  894. protected function in($value, $rule)
  895. {
  896. return in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  897. }
  898. /**
  899. * 验证是否不在某个范围
  900. * @access protected
  901. * @param mixed $value 字段值
  902. * @param mixed $rule 验证规则
  903. * @return bool
  904. */
  905. protected function notIn($value, $rule)
  906. {
  907. return !in_array($value, is_array($rule) ? $rule : explode(',', $rule));
  908. }
  909. /**
  910. * between验证数据
  911. * @access protected
  912. * @param mixed $value 字段值
  913. * @param mixed $rule 验证规则
  914. * @return bool
  915. */
  916. protected function between($value, $rule)
  917. {
  918. if (is_string($rule)) {
  919. $rule = explode(',', $rule);
  920. }
  921. list($min, $max) = $rule;
  922. return $value >= $min && $value <= $max;
  923. }
  924. /**
  925. * 使用notbetween验证数据
  926. * @access protected
  927. * @param mixed $value 字段值
  928. * @param mixed $rule 验证规则
  929. * @return bool
  930. */
  931. protected function notBetween($value, $rule)
  932. {
  933. if (is_string($rule)) {
  934. $rule = explode(',', $rule);
  935. }
  936. list($min, $max) = $rule;
  937. return $value < $min || $value > $max;
  938. }
  939. /**
  940. * 验证数据长度
  941. * @access protected
  942. * @param mixed $value 字段值
  943. * @param mixed $rule 验证规则
  944. * @return bool
  945. */
  946. protected function length($value, $rule)
  947. {
  948. if (is_array($value)) {
  949. $length = count($value);
  950. } elseif ($value instanceof File) {
  951. $length = $value->getSize();
  952. } else {
  953. $length = mb_strlen((string) $value);
  954. }
  955. if (strpos($rule, ',')) {
  956. // 长度区间
  957. list($min, $max) = explode(',', $rule);
  958. return $length >= $min && $length <= $max;
  959. } else {
  960. // 指定长度
  961. return $length == $rule;
  962. }
  963. }
  964. /**
  965. * 验证数据最大长度
  966. * @access protected
  967. * @param mixed $value 字段值
  968. * @param mixed $rule 验证规则
  969. * @return bool
  970. */
  971. protected function max($value, $rule)
  972. {
  973. if (is_array($value)) {
  974. $length = count($value);
  975. } elseif ($value instanceof File) {
  976. $length = $value->getSize();
  977. } else {
  978. $length = mb_strlen((string) $value);
  979. }
  980. return $length <= $rule;
  981. }
  982. /**
  983. * 验证数据最小长度
  984. * @access protected
  985. * @param mixed $value 字段值
  986. * @param mixed $rule 验证规则
  987. * @return bool
  988. */
  989. protected function min($value, $rule)
  990. {
  991. if (is_array($value)) {
  992. $length = count($value);
  993. } elseif ($value instanceof File) {
  994. $length = $value->getSize();
  995. } else {
  996. $length = mb_strlen((string) $value);
  997. }
  998. return $length >= $rule;
  999. }
  1000. /**
  1001. * 验证日期
  1002. * @access protected
  1003. * @param mixed $value 字段值
  1004. * @param mixed $rule 验证规则
  1005. * @return bool
  1006. */
  1007. protected function after($value, $rule)
  1008. {
  1009. return strtotime($value) >= strtotime($rule);
  1010. }
  1011. /**
  1012. * 验证日期
  1013. * @access protected
  1014. * @param mixed $value 字段值
  1015. * @param mixed $rule 验证规则
  1016. * @return bool
  1017. */
  1018. protected function before($value, $rule)
  1019. {
  1020. return strtotime($value) <= strtotime($rule);
  1021. }
  1022. /**
  1023. * 验证有效期
  1024. * @access protected
  1025. * @param mixed $value 字段值
  1026. * @param mixed $rule 验证规则
  1027. * @return bool
  1028. */
  1029. protected function expire($value, $rule)
  1030. {
  1031. if (is_string($rule)) {
  1032. $rule = explode(',', $rule);
  1033. }
  1034. list($start, $end) = $rule;
  1035. if (!is_numeric($start)) {
  1036. $start = strtotime($start);
  1037. }
  1038. if (!is_numeric($end)) {
  1039. $end = strtotime($end);
  1040. }
  1041. return $_SERVER['REQUEST_TIME'] >= $start && $_SERVER['REQUEST_TIME'] <= $end;
  1042. }
  1043. /**
  1044. * 验证IP许可
  1045. * @access protected
  1046. * @param string $value 字段值
  1047. * @param mixed $rule 验证规则
  1048. * @return mixed
  1049. */
  1050. protected function allowIp($value, $rule)
  1051. {
  1052. return in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1053. }
  1054. /**
  1055. * 验证IP禁用
  1056. * @access protected
  1057. * @param string $value 字段值
  1058. * @param mixed $rule 验证规则
  1059. * @return mixed
  1060. */
  1061. protected function denyIp($value, $rule)
  1062. {
  1063. return !in_array($_SERVER['REMOTE_ADDR'], is_array($rule) ? $rule : explode(',', $rule));
  1064. }
  1065. /**
  1066. * 使用正则验证数据
  1067. * @access protected
  1068. * @param mixed $value 字段值
  1069. * @param mixed $rule 验证规则 正则规则或者预定义正则名
  1070. * @return mixed
  1071. */
  1072. protected function regex($value, $rule)
  1073. {
  1074. if (isset($this->regex[$rule])) {
  1075. $rule = $this->regex[$rule];
  1076. }
  1077. if (0 !== strpos($rule, '/') && !preg_match('/\/[imsU]{0,4}$/', $rule)) {
  1078. // 不是正则表达式则两端补上/
  1079. $rule = '/^' . $rule . '$/';
  1080. }
  1081. return 1 === preg_match($rule, (string) $value);
  1082. }
  1083. /**
  1084. * 验证表单令牌
  1085. * @access protected
  1086. * @param mixed $value 字段值
  1087. * @param mixed $rule 验证规则
  1088. * @param array $data 数据
  1089. * @return bool
  1090. */
  1091. protected function token($value, $rule, $data)
  1092. {
  1093. $rule = !empty($rule) ? $rule : '__token__';
  1094. if (!isset($data[$rule]) || !Session::has($rule)) {
  1095. // 令牌数据无效
  1096. return false;
  1097. }
  1098. // 令牌验证
  1099. if (isset($data[$rule]) && Session::get($rule) === $data[$rule]) {
  1100. // 防止重复提交
  1101. Session::delete($rule); // 验证完成销毁session
  1102. return true;
  1103. }
  1104. // 开启TOKEN重置
  1105. Session::delete($rule);
  1106. return false;
  1107. }
  1108. // 获取错误信息
  1109. public function getError()
  1110. {
  1111. return $this->error;
  1112. }
  1113. /**
  1114. * 获取数据值
  1115. * @access protected
  1116. * @param array $data 数据
  1117. * @param string $key 数据标识 支持二维
  1118. * @return mixed
  1119. */
  1120. protected function getDataValue($data, $key)
  1121. {
  1122. if (is_numeric($key)) {
  1123. $value = $key;
  1124. } elseif (strpos($key, '.')) {
  1125. // 支持二维数组验证
  1126. list($name1, $name2) = explode('.', $key);
  1127. $value = isset($data[$name1][$name2]) ? $data[$name1][$name2] : null;
  1128. } else {
  1129. $value = isset($data[$key]) ? $data[$key] : null;
  1130. }
  1131. return $value;
  1132. }
  1133. /**
  1134. * 获取验证规则的错误提示信息
  1135. * @access protected
  1136. * @param string $attribute 字段英文名
  1137. * @param string $title 字段描述名
  1138. * @param string $type 验证规则名称
  1139. * @param mixed $rule 验证规则数据
  1140. * @return string
  1141. */
  1142. protected function getRuleMsg($attribute, $title, $type, $rule)
  1143. {
  1144. if (isset($this->message[$attribute . '.' . $type])) {
  1145. $msg = $this->message[$attribute . '.' . $type];
  1146. } elseif (isset($this->message[$attribute][$type])) {
  1147. $msg = $this->message[$attribute][$type];
  1148. } elseif (isset($this->message[$attribute])) {
  1149. $msg = $this->message[$attribute];
  1150. } elseif (isset(self::$typeMsg[$type])) {
  1151. $msg = self::$typeMsg[$type];
  1152. } elseif (0 === strpos($type, 'require')) {
  1153. $msg = self::$typeMsg['require'];
  1154. } else {
  1155. $msg = $title . '规则错误';
  1156. }
  1157. if (is_string($msg) && 0 === strpos($msg, '{%')) {
  1158. $msg = Lang::get(substr($msg, 2, -1));
  1159. }
  1160. if (is_string($msg) && is_scalar($rule) && false !== strpos($msg, ':')) {
  1161. // 变量替换
  1162. if (is_string($rule) && strpos($rule, ',')) {
  1163. $array = array_pad(explode(',', $rule), 3, '');
  1164. } else {
  1165. $array = array_pad([], 3, '');
  1166. }
  1167. $msg = str_replace(
  1168. [':attribute', ':rule', ':1', ':2', ':3'],
  1169. [$title, (string) $rule, $array[0], $array[1], $array[2]],
  1170. $msg);
  1171. }
  1172. return $msg;
  1173. }
  1174. /**
  1175. * 获取数据验证的场景
  1176. * @access protected
  1177. * @param string $scene 验证场景
  1178. * @return array
  1179. */
  1180. protected function getScene($scene = '')
  1181. {
  1182. if (empty($scene)) {
  1183. // 读取指定场景
  1184. $scene = $this->currentScene;
  1185. }
  1186. if (!empty($scene) && isset($this->scene[$scene])) {
  1187. // 如果设置了验证适用场景
  1188. $scene = $this->scene[$scene];
  1189. if (is_string($scene)) {
  1190. $scene = explode(',', $scene);
  1191. }
  1192. } else {
  1193. $scene = [];
  1194. }
  1195. return $scene;
  1196. }
  1197. public static function __callStatic($method, $params)
  1198. {
  1199. $class = self::make();
  1200. if (method_exists($class, $method)) {
  1201. return call_user_func_array([$class, $method], $params);
  1202. } else {
  1203. throw new \BadMethodCallException('method not exists:' . __CLASS__ . '->' . $method);
  1204. }
  1205. }
  1206. }