Validation.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. <?php
  2. /**
  3. * PHP Version 5.x
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @since CakePHP(tm) v 1.2.0.3830
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. App::uses('Multibyte', 'I18n');
  18. App::uses('File', 'Utility');
  19. App::uses('CakeNumber', 'Utility');
  20. // Load multibyte if the extension is missing.
  21. if (!function_exists('mb_strlen')) {
  22. class_exists('Multibyte');
  23. }
  24. /**
  25. * Validation Class. Used for validation of model data
  26. *
  27. * Offers different validation methods.
  28. *
  29. * @package Cake.Utility
  30. */
  31. class Validation {
  32. /**
  33. * Some complex patterns needed in multiple places
  34. *
  35. * @var array
  36. */
  37. protected static $_pattern = array(
  38. 'hostname' => '(?:[_a-z0-9][-_a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,})'
  39. );
  40. /**
  41. * Holds an array of errors messages set in this class.
  42. * These are used for debugging purposes
  43. *
  44. * @var array
  45. */
  46. public static $errors = array();
  47. /**
  48. * Checks that a string contains something other than whitespace
  49. *
  50. * Returns true if string contains something other than whitespace
  51. *
  52. * $check can be passed as an array:
  53. * array('check' => 'valueToCheck');
  54. *
  55. * @param string|array $check Value to check
  56. * @return boolean Success
  57. */
  58. public static function notEmpty($check) {
  59. if (is_array($check)) {
  60. extract(self::_defaults($check));
  61. }
  62. if (empty($check) && $check != '0') {
  63. return false;
  64. }
  65. return self::_check($check, '/[^\s]+/m');
  66. }
  67. /**
  68. * Checks that a string contains only integer or letters
  69. *
  70. * Returns true if string contains only integer or letters
  71. *
  72. * $check can be passed as an array:
  73. * array('check' => 'valueToCheck');
  74. *
  75. * @param string|array $check Value to check
  76. * @return boolean Success
  77. */
  78. public static function alphaNumeric($check) {
  79. if (is_array($check)) {
  80. extract(self::_defaults($check));
  81. }
  82. if (empty($check) && $check != '0') {
  83. return false;
  84. }
  85. return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
  86. }
  87. /**
  88. * Checks that a string length is within s specified range.
  89. * Spaces are included in the character count.
  90. * Returns true is string matches value min, max, or between min and max,
  91. *
  92. * @param string $check Value to check for length
  93. * @param integer $min Minimum value in range (inclusive)
  94. * @param integer $max Maximum value in range (inclusive)
  95. * @return boolean Success
  96. */
  97. public static function between($check, $min, $max) {
  98. $length = mb_strlen($check);
  99. return ($length >= $min && $length <= $max);
  100. }
  101. /**
  102. * Returns true if field is left blank -OR- only whitespace characters are present in its value
  103. * Whitespace characters include Space, Tab, Carriage Return, Newline
  104. *
  105. * $check can be passed as an array:
  106. * array('check' => 'valueToCheck');
  107. *
  108. * @param string|array $check Value to check
  109. * @return boolean Success
  110. */
  111. public static function blank($check) {
  112. if (is_array($check)) {
  113. extract(self::_defaults($check));
  114. }
  115. return !self::_check($check, '/[^\\s]/');
  116. }
  117. /**
  118. * Validation of credit card numbers.
  119. * Returns true if $check is in the proper credit card format.
  120. *
  121. * @param string|array $check credit card number to validate
  122. * @param string|array $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit cards
  123. * if an array is used only the values of the array are checked.
  124. * Example: array('amex', 'bankcard', 'maestro')
  125. * @param boolean $deep set to true this will check the Luhn algorithm of the credit card.
  126. * @param string $regex A custom regex can also be passed, this will be used instead of the defined regex values
  127. * @return boolean Success
  128. * @see Validation::luhn()
  129. */
  130. public static function cc($check, $type = 'fast', $deep = false, $regex = null) {
  131. if (is_array($check)) {
  132. extract(self::_defaults($check));
  133. }
  134. $check = str_replace(array('-', ' '), '', $check);
  135. if (mb_strlen($check) < 13) {
  136. return false;
  137. }
  138. if (!is_null($regex)) {
  139. if (self::_check($check, $regex)) {
  140. return self::luhn($check, $deep);
  141. }
  142. }
  143. $cards = array(
  144. 'all' => array(
  145. 'amex' => '/^3[4|7]\\d{13}$/',
  146. 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
  147. 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
  148. 'disc' => '/^(?:6011|650\\d)\\d{12}$/',
  149. 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
  150. 'enroute' => '/^2(?:014|149)\\d{11}$/',
  151. 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
  152. 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/',
  153. 'mc' => '/^5[1-5]\\d{14}$/',
  154. 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
  155. 'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
  156. 'visa' => '/^4\\d{12}(\\d{3})?$/',
  157. 'voyager' => '/^8699[0-9]{11}$/'
  158. ),
  159. 'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
  160. );
  161. if (is_array($type)) {
  162. foreach ($type as $value) {
  163. $regex = $cards['all'][strtolower($value)];
  164. if (self::_check($check, $regex)) {
  165. return self::luhn($check, $deep);
  166. }
  167. }
  168. } elseif ($type === 'all') {
  169. foreach ($cards['all'] as $value) {
  170. $regex = $value;
  171. if (self::_check($check, $regex)) {
  172. return self::luhn($check, $deep);
  173. }
  174. }
  175. } else {
  176. $regex = $cards['fast'];
  177. if (self::_check($check, $regex)) {
  178. return self::luhn($check, $deep);
  179. }
  180. }
  181. return false;
  182. }
  183. /**
  184. * Used to compare 2 numeric values.
  185. *
  186. * @param string|array $check1 if string is passed for a string must also be passed for $check2
  187. * used as an array it must be passed as array('check1' => value, 'operator' => 'value', 'check2' -> value)
  188. * @param string $operator Can be either a word or operand
  189. * is greater >, is less <, greater or equal >=
  190. * less or equal <=, is less <, equal to ==, not equal !=
  191. * @param integer $check2 only needed if $check1 is a string
  192. * @return boolean Success
  193. */
  194. public static function comparison($check1, $operator = null, $check2 = null) {
  195. if (is_array($check1)) {
  196. extract($check1, EXTR_OVERWRITE);
  197. }
  198. $operator = str_replace(array(' ', "\t", "\n", "\r", "\0", "\x0B"), '', strtolower($operator));
  199. switch ($operator) {
  200. case 'isgreater':
  201. case '>':
  202. if ($check1 > $check2) {
  203. return true;
  204. }
  205. break;
  206. case 'isless':
  207. case '<':
  208. if ($check1 < $check2) {
  209. return true;
  210. }
  211. break;
  212. case 'greaterorequal':
  213. case '>=':
  214. if ($check1 >= $check2) {
  215. return true;
  216. }
  217. break;
  218. case 'lessorequal':
  219. case '<=':
  220. if ($check1 <= $check2) {
  221. return true;
  222. }
  223. break;
  224. case 'equalto':
  225. case '==':
  226. if ($check1 == $check2) {
  227. return true;
  228. }
  229. break;
  230. case 'notequal':
  231. case '!=':
  232. if ($check1 != $check2) {
  233. return true;
  234. }
  235. break;
  236. default:
  237. self::$errors[] = __d('cake_dev', 'You must define the $operator parameter for Validation::comparison()');
  238. break;
  239. }
  240. return false;
  241. }
  242. /**
  243. * Used when a custom regular expression is needed.
  244. *
  245. * @param string|array $check When used as a string, $regex must also be a valid regular expression.
  246. * As and array: array('check' => value, 'regex' => 'valid regular expression')
  247. * @param string $regex If $check is passed as a string, $regex must also be set to valid regular expression
  248. * @return boolean Success
  249. */
  250. public static function custom($check, $regex = null) {
  251. if (is_array($check)) {
  252. extract(self::_defaults($check));
  253. }
  254. if ($regex === null) {
  255. self::$errors[] = __d('cake_dev', 'You must define a regular expression for Validation::custom()');
  256. return false;
  257. }
  258. return self::_check($check, $regex);
  259. }
  260. /**
  261. * Date validation, determines if the string passed is a valid date.
  262. * keys that expect full month, day and year will validate leap years
  263. *
  264. * @param string $check a valid date string
  265. * @param string|array $format Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc)
  266. * Keys: dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  267. * mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  268. * ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  269. * dMy 27 December 2006 or 27 Dec 2006
  270. * Mdy December 27, 2006 or Dec 27, 2006 comma is optional
  271. * My December 2006 or Dec 2006
  272. * my 12/2006 separators can be a space, period, dash, forward slash
  273. * @param string $regex If a custom regular expression is used this is the only validation that will occur.
  274. * @return boolean Success
  275. */
  276. public static function date($check, $format = 'ymd', $regex = null) {
  277. if (!is_null($regex)) {
  278. return self::_check($check, $regex);
  279. }
  280. $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.|\\x20)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.|\\x20)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.|\\x20)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  281. $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])(\\/|-|\\.|\\x20)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2(\\/|-|\\.|\\x20)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.|\\x20)(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
  282. $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(\\/|-|\\.|\\x20)(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})(\\/|-|\\.|\\x20)(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]))))$%';
  283. $regex['dMy'] = '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]\\d)\\d{2})$/';
  284. $regex['Mdy'] = '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep)(tember)?|(Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/';
  285. $regex['My'] = '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)[ /]((1[6-9]|[2-9]\\d)\\d{2})$%';
  286. $regex['my'] = '%^((0[123456789]|10|11|12)([- /.])(([1][9][0-9][0-9])|([2][0-9][0-9][0-9])))$%';
  287. $format = (is_array($format)) ? array_values($format) : array($format);
  288. foreach ($format as $key) {
  289. if (self::_check($check, $regex[$key]) === true) {
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. /**
  296. * Validates a datetime value
  297. * All values matching the "date" core validation rule, and the "time" one will be valid
  298. *
  299. * @param string $check Value to check
  300. * @param string|array $dateFormat Format of the date part
  301. * Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc)
  302. * ## Keys:
  303. *
  304. * - dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
  305. * - mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
  306. * - ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
  307. * - dMy 27 December 2006 or 27 Dec 2006
  308. * - Mdy December 27, 2006 or Dec 27, 2006 comma is optional
  309. * - My December 2006 or Dec 2006
  310. * - my 12/2006 separators can be a space, period, dash, forward slash
  311. * @param string $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
  312. * @return boolean True if the value is valid, false otherwise
  313. * @see Validation::date
  314. * @see Validation::time
  315. */
  316. public static function datetime($check, $dateFormat = 'ymd', $regex = null) {
  317. $valid = false;
  318. $parts = explode(' ', $check);
  319. if (!empty($parts) && count($parts) > 1) {
  320. $time = array_pop($parts);
  321. $date = implode(' ', $parts);
  322. $valid = self::date($date, $dateFormat, $regex) && self::time($time);
  323. }
  324. return $valid;
  325. }
  326. /**
  327. * Time validation, determines if the string passed is a valid time.
  328. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
  329. * Does not allow/validate seconds.
  330. *
  331. * @param string $check a valid time string
  332. * @return boolean Success
  333. */
  334. public static function time($check) {
  335. return self::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%');
  336. }
  337. /**
  338. * Boolean validation, determines if value passed is a boolean integer or true/false.
  339. *
  340. * @param string $check a valid boolean
  341. * @return boolean Success
  342. */
  343. public static function boolean($check) {
  344. $booleanList = array(0, 1, '0', '1', true, false);
  345. return in_array($check, $booleanList, true);
  346. }
  347. /**
  348. * Checks that a value is a valid decimal. Both the sign and exponent are optional.
  349. *
  350. * Valid Places:
  351. *
  352. * - null => Any number of decimal places, including none. The '.' is not required.
  353. * - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
  354. * - 1..N => Exactly that many number of decimal places. The '.' is required.
  355. *
  356. * @param float $check The value the test for decimal
  357. * @param integer $places
  358. * @param string $regex If a custom regular expression is used, this is the only validation that will occur.
  359. * @return boolean Success
  360. */
  361. public static function decimal($check, $places = null, $regex = null) {
  362. if (is_null($regex)) {
  363. $lnum = '[0-9]+';
  364. $dnum = "[0-9]*[\.]{$lnum}";
  365. $sign = '[+-]?';
  366. $exp = "(?:[eE]{$sign}{$lnum})?";
  367. if ($places === null) {
  368. $regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
  369. } elseif ($places === true) {
  370. if (is_float($check) && floor($check) === $check) {
  371. $check = sprintf("%.1f", $check);
  372. }
  373. $regex = "/^{$sign}{$dnum}{$exp}$/";
  374. } elseif (is_numeric($places)) {
  375. $places = '[0-9]{' . $places . '}';
  376. $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
  377. $regex = "/^{$sign}{$dnum}{$exp}$/";
  378. }
  379. }
  380. return self::_check($check, $regex);
  381. }
  382. /**
  383. * Validates for an email address.
  384. *
  385. * Only uses getmxrr() checking for deep validation if PHP 5.3.0+ is used, or
  386. * any PHP version on a non-windows distribution
  387. *
  388. * @param string $check Value to check
  389. * @param boolean $deep Perform a deeper validation (if true), by also checking availability of host
  390. * @param string $regex Regex to use (if none it will use built in regex)
  391. * @return boolean Success
  392. */
  393. public static function email($check, $deep = false, $regex = null) {
  394. if (is_array($check)) {
  395. extract(self::_defaults($check));
  396. }
  397. if (is_null($regex)) {
  398. $regex = '/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/i';
  399. }
  400. $return = self::_check($check, $regex);
  401. if ($deep === false || $deep === null) {
  402. return $return;
  403. }
  404. if ($return === true && preg_match('/@(' . self::$_pattern['hostname'] . ')$/i', $check, $regs)) {
  405. if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
  406. return true;
  407. }
  408. if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
  409. return true;
  410. }
  411. return is_array(gethostbynamel($regs[1]));
  412. }
  413. return false;
  414. }
  415. /**
  416. * Check that value is exactly $comparedTo.
  417. *
  418. * @param mixed $check Value to check
  419. * @param mixed $comparedTo Value to compare
  420. * @return boolean Success
  421. */
  422. public static function equalTo($check, $comparedTo) {
  423. return ($check === $comparedTo);
  424. }
  425. /**
  426. * Check that value has a valid file extension.
  427. *
  428. * @param string|array $check Value to check
  429. * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
  430. * @return boolean Success
  431. */
  432. public static function extension($check, $extensions = array('gif', 'jpeg', 'png', 'jpg')) {
  433. if (is_array($check)) {
  434. return self::extension(array_shift($check), $extensions);
  435. }
  436. $extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
  437. foreach ($extensions as $value) {
  438. if ($extension === strtolower($value)) {
  439. return true;
  440. }
  441. }
  442. return false;
  443. }
  444. /**
  445. * Validation of an IP address.
  446. *
  447. * @param string $check The string to test.
  448. * @param string $type The IP Protocol version to validate against
  449. * @return boolean Success
  450. */
  451. public static function ip($check, $type = 'both') {
  452. $type = strtolower($type);
  453. $flags = 0;
  454. if ($type === 'ipv4') {
  455. $flags = FILTER_FLAG_IPV4;
  456. }
  457. if ($type === 'ipv6') {
  458. $flags = FILTER_FLAG_IPV6;
  459. }
  460. return (boolean)filter_var($check, FILTER_VALIDATE_IP, array('flags' => $flags));
  461. }
  462. /**
  463. * Checks whether the length of a string is greater or equal to a minimal length.
  464. *
  465. * @param string $check The string to test
  466. * @param integer $min The minimal string length
  467. * @return boolean Success
  468. */
  469. public static function minLength($check, $min) {
  470. return mb_strlen($check) >= $min;
  471. }
  472. /**
  473. * Checks whether the length of a string is smaller or equal to a maximal length..
  474. *
  475. * @param string $check The string to test
  476. * @param integer $max The maximal string length
  477. * @return boolean Success
  478. */
  479. public static function maxLength($check, $max) {
  480. return mb_strlen($check) <= $max;
  481. }
  482. /**
  483. * Checks that a value is a monetary amount.
  484. *
  485. * @param string $check Value to check
  486. * @param string $symbolPosition Where symbol is located (left/right)
  487. * @return boolean Success
  488. */
  489. public static function money($check, $symbolPosition = 'left') {
  490. $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
  491. if ($symbolPosition === 'right') {
  492. $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
  493. } else {
  494. $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
  495. }
  496. return self::_check($check, $regex);
  497. }
  498. /**
  499. * Validate a multiple select.
  500. *
  501. * Valid Options
  502. *
  503. * - in => provide a list of choices that selections must be made from
  504. * - max => maximum number of non-zero choices that can be made
  505. * - min => minimum number of non-zero choices that can be made
  506. *
  507. * @param array $check Value to check
  508. * @param array $options Options for the check.
  509. * @param boolean $strict Defaults to true, set to false to disable strict type check
  510. * @return boolean Success
  511. */
  512. public static function multiple($check, $options = array(), $strict = true) {
  513. $defaults = array('in' => null, 'max' => null, 'min' => null);
  514. $options = array_merge($defaults, $options);
  515. $check = array_filter((array)$check);
  516. if (empty($check)) {
  517. return false;
  518. }
  519. if ($options['max'] && count($check) > $options['max']) {
  520. return false;
  521. }
  522. if ($options['min'] && count($check) < $options['min']) {
  523. return false;
  524. }
  525. if ($options['in'] && is_array($options['in'])) {
  526. foreach ($check as $val) {
  527. if (!in_array($val, $options['in'], $strict)) {
  528. return false;
  529. }
  530. }
  531. }
  532. return true;
  533. }
  534. /**
  535. * Checks if a value is numeric.
  536. *
  537. * @param string $check Value to check
  538. * @return boolean Success
  539. */
  540. public static function numeric($check) {
  541. return is_numeric($check);
  542. }
  543. /**
  544. * Checks if a value is a natural number.
  545. *
  546. * @param string $check Value to check
  547. * @param boolean $allowZero Set true to allow zero, defaults to false
  548. * @return boolean Success
  549. * @see http://en.wikipedia.org/wiki/Natural_number
  550. */
  551. public static function naturalNumber($check, $allowZero = false) {
  552. $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
  553. return self::_check($check, $regex);
  554. }
  555. /**
  556. * Check that a value is a valid phone number.
  557. *
  558. * @param string|array $check Value to check (string or array)
  559. * @param string $regex Regular expression to use
  560. * @param string $country Country code (defaults to 'all')
  561. * @return boolean Success
  562. */
  563. public static function phone($check, $regex = null, $country = 'all') {
  564. if (is_array($check)) {
  565. extract(self::_defaults($check));
  566. }
  567. if (is_null($regex)) {
  568. switch ($country) {
  569. case 'us':
  570. case 'all':
  571. case 'can':
  572. // includes all NANPA members.
  573. // see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories
  574. $regex = '/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/';
  575. break;
  576. }
  577. }
  578. if (empty($regex)) {
  579. return self::_pass('phone', $check, $country);
  580. }
  581. return self::_check($check, $regex);
  582. }
  583. /**
  584. * Checks that a given value is a valid postal code.
  585. *
  586. * @param string|array $check Value to check
  587. * @param string $regex Regular expression to use
  588. * @param string $country Country to use for formatting
  589. * @return boolean Success
  590. */
  591. public static function postal($check, $regex = null, $country = 'us') {
  592. if (is_array($check)) {
  593. extract(self::_defaults($check));
  594. }
  595. if (is_null($regex)) {
  596. switch ($country) {
  597. case 'uk':
  598. $regex = '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i';
  599. break;
  600. case 'ca':
  601. $district = '[ABCEGHJKLMNPRSTVYX]';
  602. $letters = '[ABCEGHJKLMNPRSTVWXYZ]';
  603. $regex = "/\\A\\b{$district}[0-9]{$letters} [0-9]{$letters}[0-9]\\b\\z/i";
  604. break;
  605. case 'it':
  606. case 'de':
  607. $regex = '/^[0-9]{5}$/i';
  608. break;
  609. case 'be':
  610. $regex = '/^[1-9]{1}[0-9]{3}$/i';
  611. break;
  612. case 'us':
  613. $regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i';
  614. break;
  615. }
  616. }
  617. if (empty($regex)) {
  618. return self::_pass('postal', $check, $country);
  619. }
  620. return self::_check($check, $regex);
  621. }
  622. /**
  623. * Validate that a number is in specified range.
  624. * if $lower and $upper are not set, will return true if
  625. * $check is a legal finite on this platform
  626. *
  627. * @param string $check Value to check
  628. * @param integer $lower Lower limit
  629. * @param integer $upper Upper limit
  630. * @return boolean Success
  631. */
  632. public static function range($check, $lower = null, $upper = null) {
  633. if (!is_numeric($check)) {
  634. return false;
  635. }
  636. if (isset($lower) && isset($upper)) {
  637. return ($check > $lower && $check < $upper);
  638. }
  639. return is_finite($check);
  640. }
  641. /**
  642. * Checks that a value is a valid Social Security Number.
  643. *
  644. * @param string|array $check Value to check
  645. * @param string $regex Regular expression to use
  646. * @param string $country Country
  647. * @return boolean Success
  648. */
  649. public static function ssn($check, $regex = null, $country = null) {
  650. if (is_array($check)) {
  651. extract(self::_defaults($check));
  652. }
  653. if (is_null($regex)) {
  654. switch ($country) {
  655. case 'dk':
  656. $regex = '/\\A\\b[0-9]{6}-[0-9]{4}\\b\\z/i';
  657. break;
  658. case 'nl':
  659. $regex = '/\\A\\b[0-9]{9}\\b\\z/i';
  660. break;
  661. case 'us':
  662. $regex = '/\\A\\b[0-9]{3}-[0-9]{2}-[0-9]{4}\\b\\z/i';
  663. break;
  664. }
  665. }
  666. if (empty($regex)) {
  667. return self::_pass('ssn', $check, $country);
  668. }
  669. return self::_check($check, $regex);
  670. }
  671. /**
  672. * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
  673. *
  674. * The regex checks for the following component parts:
  675. *
  676. * - a valid, optional, scheme
  677. * - a valid ip address OR
  678. * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
  679. * with an optional port number
  680. * - an optional valid path
  681. * - an optional query string (get parameters)
  682. * - an optional fragment (anchor tag)
  683. *
  684. * @param string $check Value to check
  685. * @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
  686. * @return boolean Success
  687. */
  688. public static function url($check, $strict = false) {
  689. self::_populateIp();
  690. $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9a-z\p{L}\p{N}]|(%[0-9a-f]{2}))';
  691. $regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
  692. '(?:' . self::$_pattern['IPv4'] . '|\[' . self::$_pattern['IPv6'] . '\]|' . self::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
  693. '(?:\/?|\/' . $validChars . '*)?' .
  694. '(?:\?' . $validChars . '*)?' .
  695. '(?:#' . $validChars . '*)?$/iu';
  696. return self::_check($check, $regex);
  697. }
  698. /**
  699. * Checks if a value is in a given list.
  700. *
  701. * @param string $check Value to check
  702. * @param array $list List to check against
  703. * @param boolean $strict Defaults to true, set to false to disable strict type check
  704. * @return boolean Success
  705. */
  706. public static function inList($check, $list, $strict = true) {
  707. return in_array($check, $list, $strict);
  708. }
  709. /**
  710. * Runs an user-defined validation.
  711. *
  712. * @param string|array $check value that will be validated in user-defined methods.
  713. * @param object $object class that holds validation method
  714. * @param string $method class method name for validation to run
  715. * @param array $args arguments to send to method
  716. * @return mixed user-defined class class method returns
  717. */
  718. public static function userDefined($check, $object, $method, $args = null) {
  719. return call_user_func_array(array($object, $method), array($check, $args));
  720. }
  721. /**
  722. * Checks that a value is a valid uuid - http://tools.ietf.org/html/rfc4122
  723. *
  724. * @param string $check Value to check
  725. * @return boolean Success
  726. */
  727. public static function uuid($check) {
  728. $regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[1-5][a-fA-F0-9]{3}-[89aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/';
  729. return self::_check($check, $regex);
  730. }
  731. /**
  732. * Attempts to pass unhandled Validation locales to a class starting with $classPrefix
  733. * and ending with Validation. For example $classPrefix = 'nl', the class would be
  734. * `NlValidation`.
  735. *
  736. * @param string $method The method to call on the other class.
  737. * @param mixed $check The value to check or an array of parameters for the method to be called.
  738. * @param string $classPrefix The prefix for the class to do the validation.
  739. * @return mixed Return of Passed method, false on failure
  740. */
  741. protected static function _pass($method, $check, $classPrefix) {
  742. $className = ucwords($classPrefix) . 'Validation';
  743. if (!class_exists($className)) {
  744. trigger_error(__d('cake_dev', 'Could not find %s class, unable to complete validation.', $className), E_USER_WARNING);
  745. return false;
  746. }
  747. if (!method_exists($className, $method)) {
  748. trigger_error(__d('cake_dev', 'Method %s does not exist on %s unable to complete validation.', $method, $className), E_USER_WARNING);
  749. return false;
  750. }
  751. $check = (array)$check;
  752. return call_user_func_array(array($className, $method), $check);
  753. }
  754. /**
  755. * Runs a regular expression match.
  756. *
  757. * @param string $check Value to check against the $regex expression
  758. * @param string $regex Regular expression
  759. * @return boolean Success of match
  760. */
  761. protected static function _check($check, $regex) {
  762. if (is_string($regex) && preg_match($regex, $check)) {
  763. return true;
  764. } else {
  765. return false;
  766. }
  767. }
  768. /**
  769. * Get the values to use when value sent to validation method is
  770. * an array.
  771. *
  772. * @param array $params Parameters sent to validation method
  773. * @return void
  774. */
  775. protected static function _defaults($params) {
  776. self::_reset();
  777. $defaults = array(
  778. 'check' => null,
  779. 'regex' => null,
  780. 'country' => null,
  781. 'deep' => false,
  782. 'type' => null
  783. );
  784. $params = array_merge($defaults, $params);
  785. if ($params['country'] !== null) {
  786. $params['country'] = mb_strtolower($params['country']);
  787. }
  788. return $params;
  789. }
  790. /**
  791. * Luhn algorithm
  792. *
  793. * @param string|array $check
  794. * @param boolean $deep
  795. * @return boolean Success
  796. * @see http://en.wikipedia.org/wiki/Luhn_algorithm
  797. */
  798. public static function luhn($check, $deep = false) {
  799. if (is_array($check)) {
  800. extract(self::_defaults($check));
  801. }
  802. if ($deep !== true) {
  803. return true;
  804. }
  805. if ((int)$check === 0) {
  806. return false;
  807. }
  808. $sum = 0;
  809. $length = strlen($check);
  810. for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
  811. $sum += $check[$position];
  812. }
  813. for ($position = ($length % 2); $position < $length; $position += 2) {
  814. $number = $check[$position] * 2;
  815. $sum += ($number < 10) ? $number : $number - 9;
  816. }
  817. return ($sum % 10 === 0);
  818. }
  819. /**
  820. * Checks the mime type of a file
  821. *
  822. * @param string|array $check
  823. * @param array $mimeTypes to check for
  824. * @return boolean Success
  825. * @throws CakeException when mime type can not be determined.
  826. */
  827. public static function mimeType($check, $mimeTypes = array()) {
  828. if (is_array($check) && isset($check['tmp_name'])) {
  829. $check = $check['tmp_name'];
  830. }
  831. $File = new File($check);
  832. $mime = $File->mime();
  833. if ($mime === false) {
  834. throw new CakeException(__d('cake_dev', 'Can not determine the mimetype.'));
  835. }
  836. return in_array($mime, $mimeTypes);
  837. }
  838. /**
  839. * Checks the filesize
  840. *
  841. * @param string|array $check
  842. * @param integer|string $size Size in bytes or human readable string like '5MB'
  843. * @param string $operator See `Validation::comparison()`
  844. * @return boolean Success
  845. */
  846. public static function fileSize($check, $operator = null, $size = null) {
  847. if (is_array($check) && isset($check['tmp_name'])) {
  848. $check = $check['tmp_name'];
  849. }
  850. if (is_string($size)) {
  851. $size = CakeNumber::fromReadableSize($size);
  852. }
  853. $filesize = filesize($check);
  854. return self::comparison($filesize, $operator, $size);
  855. }
  856. /**
  857. * Checking for upload errors
  858. *
  859. * @param string|array $check
  860. * @return boolean
  861. * @see http://www.php.net/manual/en/features.file-upload.errors.php
  862. */
  863. public static function uploadError($check) {
  864. if (is_array($check) && isset($check['error'])) {
  865. $check = $check['error'];
  866. }
  867. return $check === UPLOAD_ERR_OK;
  868. }
  869. /**
  870. * Lazily populate the IP address patterns used for validations
  871. *
  872. * @return void
  873. */
  874. protected static function _populateIp() {
  875. if (!isset(self::$_pattern['IPv6'])) {
  876. $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
  877. $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
  878. $pattern .= '|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})';
  879. $pattern .= '(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)';
  880. $pattern .= '{4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  881. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}';
  882. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
  883. $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
  884. $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
  885. $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
  886. $pattern .= '{0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)';
  887. $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
  888. $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
  889. $pattern .= '{1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?';
  890. self::$_pattern['IPv6'] = $pattern;
  891. }
  892. if (!isset(self::$_pattern['IPv4'])) {
  893. $pattern = '(?:(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])';
  894. self::$_pattern['IPv4'] = $pattern;
  895. }
  896. }
  897. /**
  898. * Reset internal variables for another validation run.
  899. *
  900. * @return void
  901. */
  902. protected static function _reset() {
  903. self::$errors = array();
  904. }
  905. }