Validate.php 43 KB

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