Validate.php 43 KB

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