Validate.php 42 KB

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