Validate.php 41 KB

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