CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.0 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.0
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Auth
    • Core
    • Error
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs