PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/libs/validation.php

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