Validation.php 29 KB

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