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.1 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 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
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeNumber
  • CakeTime
  • 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-2012, 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-2012, 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 = 0;
471:         if ($type === 'ipv4') {
472:             $flags = FILTER_FLAG_IPV4;
473:         }
474:         if ($type === 'ipv6') {
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'], true)) {
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.
584:                     // see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories
585:                     $regex  = '/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/';
586:                 break;
587:             }
588:         }
589:         if (empty($regex)) {
590:             return self::_pass('phone', $check, $country);
591:         }
592:         return self::_check($check, $regex);
593:     }
594: 
595: /**
596:  * Checks that a given value is a valid postal code.
597:  *
598:  * @param mixed $check Value to check
599:  * @param string $regex Regular expression to use
600:  * @param string $country Country to use for formatting
601:  * @return boolean Success
602:  */
603:     public static function postal($check, $regex = null, $country = 'us') {
604:         if (is_array($check)) {
605:             extract(self::_defaults($check));
606:         }
607: 
608:         if (is_null($regex)) {
609:             switch ($country) {
610:                 case 'uk':
611:                     $regex  = '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i';
612:                     break;
613:                 case 'ca':
614:                     $regex  = '/\\A\\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\\b\\z/i';
615:                     break;
616:                 case 'it':
617:                 case 'de':
618:                     $regex  = '/^[0-9]{5}$/i';
619:                     break;
620:                 case 'be':
621:                     $regex  = '/^[1-9]{1}[0-9]{3}$/i';
622:                     break;
623:                 case 'us':
624:                     $regex  = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i';
625:                     break;
626:             }
627:         }
628:         if (empty($regex)) {
629:             return self::_pass('postal', $check, $country);
630:         }
631:         return self::_check($check, $regex);
632:     }
633: 
634: /**
635:  * Validate that a number is in specified range.
636:  * if $lower and $upper are not set, will return true if
637:  * $check is a legal finite on this platform
638:  *
639:  * @param string $check Value to check
640:  * @param integer $lower Lower limit
641:  * @param integer $upper Upper limit
642:  * @return boolean Success
643:  */
644:     public static function range($check, $lower = null, $upper = null) {
645:         if (!is_numeric($check)) {
646:             return false;
647:         }
648:         if (isset($lower) && isset($upper)) {
649:             return ($check > $lower && $check < $upper);
650:         }
651:         return is_finite($check);
652:     }
653: 
654: /**
655:  * Checks that a value is a valid Social Security Number.
656:  *
657:  * @param mixed $check Value to check
658:  * @param string $regex Regular expression to use
659:  * @param string $country Country
660:  * @return boolean Success
661:  */
662:     public static function ssn($check, $regex = null, $country = null) {
663:         if (is_array($check)) {
664:             extract(self::_defaults($check));
665:         }
666: 
667:         if (is_null($regex)) {
668:             switch ($country) {
669:                 case 'dk':
670:                     $regex  = '/\\A\\b[0-9]{6}-[0-9]{4}\\b\\z/i';
671:                     break;
672:                 case 'nl':
673:                     $regex  = '/\\A\\b[0-9]{9}\\b\\z/i';
674:                     break;
675:                 case 'us':
676:                     $regex  = '/\\A\\b[0-9]{3}-[0-9]{2}-[0-9]{4}\\b\\z/i';
677:                     break;
678:             }
679:         }
680:         if (empty($regex)) {
681:             return self::_pass('ssn', $check, $country);
682:         }
683:         return self::_check($check, $regex);
684:     }
685: 
686: /**
687:  * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
688:  *
689:  * The regex checks for the following component parts:
690:  *
691:  * - a valid, optional, scheme
692:  * - a valid ip address OR
693:  *   a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
694:  *   with an optional port number
695:  * - an optional valid path
696:  * - an optional query string (get parameters)
697:  * - an optional fragment (anchor tag)
698:  *
699:  * @param string $check Value to check
700:  * @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
701:  * @return boolean Success
702:  */
703:     public static function url($check, $strict = false) {
704:         self::_populateIp();
705:         $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9a-z\p{L}\p{N}]|(%[0-9a-f]{2}))';
706:         $regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
707:             '(?:' . self::$_pattern['IPv4'] . '|\[' . self::$_pattern['IPv6'] . '\]|' . self::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
708:             '(?:\/?|\/' . $validChars . '*)?' .
709:             '(?:\?' . $validChars . '*)?' .
710:             '(?:#' . $validChars . '*)?$/iu';
711:         return self::_check($check, $regex);
712:     }
713: 
714: /**
715:  * Checks if a value is in a given list.
716:  *
717:  * @param string $check Value to check
718:  * @param array $list List to check against
719:  * @return boolean Success
720:  */
721:     public static function inList($check, $list) {
722:         return in_array($check, $list, true);
723:     }
724: 
725: /**
726:  * Runs an user-defined validation.
727:  *
728:  * @param mixed $check value that will be validated in user-defined methods.
729:  * @param object $object class that holds validation method
730:  * @param string $method class method name for validation to run
731:  * @param array $args arguments to send to method
732:  * @return mixed user-defined class class method returns
733:  */
734:     public static function userDefined($check, $object, $method, $args = null) {
735:         return call_user_func_array(array($object, $method), array($check, $args));
736:     }
737: 
738: /**
739:  * Checks that a value is a valid uuid - http://tools.ietf.org/html/rfc4122
740:  *
741:  * @param string $check Value to check
742:  * @return boolean Success
743:  */
744:     public static function uuid($check) {
745:         $regex = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i';
746:         return self::_check($check, $regex);
747:     }
748: 
749: /**
750:  * Attempts to pass unhandled Validation locales to a class starting with $classPrefix
751:  * and ending with Validation.  For example $classPrefix = 'nl', the class would be
752:  * `NlValidation`.
753:  *
754:  * @param string $method The method to call on the other class.
755:  * @param mixed $check The value to check or an array of parameters for the method to be called.
756:  * @param string $classPrefix The prefix for the class to do the validation.
757:  * @return mixed Return of Passed method, false on failure
758:  */
759:     protected static function _pass($method, $check, $classPrefix) {
760:         $className = ucwords($classPrefix) . 'Validation';
761:         if (!class_exists($className)) {
762:             trigger_error(__d('cake_dev', 'Could not find %s class, unable to complete validation.', $className), E_USER_WARNING);
763:             return false;
764:         }
765:         if (!method_exists($className, $method)) {
766:             trigger_error(__d('cake_dev', 'Method %s does not exist on %s unable to complete validation.', $method, $className), E_USER_WARNING);
767:             return false;
768:         }
769:         $check = (array)$check;
770:         return call_user_func_array(array($className, $method), $check);
771:     }
772: 
773: /**
774:  * Runs a regular expression match.
775:  *
776:  * @param mixed $check Value to check against the $regex expression
777:  * @param string $regex Regular expression
778:  * @return boolean Success of match
779:  */
780:     protected static function _check($check, $regex) {
781:         if (preg_match($regex, $check)) {
782:             self::$errors[] = false;
783:             return true;
784:         } else {
785:             self::$errors[] = true;
786:             return false;
787:         }
788:     }
789: 
790: /**
791:  * Get the values to use when value sent to validation method is
792:  * an array.
793:  *
794:  * @param array $params Parameters sent to validation method
795:  * @return void
796:  */
797:     protected static function _defaults($params) {
798:         self::_reset();
799:         $defaults = array(
800:             'check' => null,
801:             'regex' => null,
802:             'country' => null,
803:             'deep' => false,
804:             'type' => null
805:         );
806:         $params = array_merge($defaults, $params);
807:         if ($params['country'] !== null) {
808:             $params['country'] = mb_strtolower($params['country']);
809:         }
810:         return $params;
811:     }
812: 
813: /**
814:  * Luhn algorithm
815:  *
816:  * @param string|array $check
817:  * @param boolean $deep
818:  * @return boolean Success
819:  * @see http://en.wikipedia.org/wiki/Luhn_algorithm
820:  */
821:     public static function luhn($check, $deep = false) {
822:         if (is_array($check)) {
823:             extract(self::_defaults($check));
824:         }
825:         if ($deep !== true) {
826:             return true;
827:         }
828:         if ($check == 0) {
829:             return false;
830:         }
831:         $sum = 0;
832:         $length = strlen($check);
833: 
834:         for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
835:             $sum += $check[$position];
836:         }
837: 
838:         for ($position = ($length % 2); $position < $length; $position += 2) {
839:             $number = $check[$position] * 2;
840:             $sum += ($number < 10) ? $number : $number - 9;
841:         }
842: 
843:         return ($sum % 10 == 0);
844:     }
845: 
846: /**
847:  * Lazily populate the IP address patterns used for validations
848:  *
849:  * @return void
850:  */
851:     protected static function _populateIp() {
852:         if (!isset(self::$_pattern['IPv6'])) {
853:             $pattern  = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
854:             $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
855:             $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})';
856:             $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}:)';
857:             $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}))';
858:             $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}';
859:             $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
860:             $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
861:             $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
862:             $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
863:             $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})?)';
864:             $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
865:             $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
866:             $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})))(%.+)?';
867: 
868:             self::$_pattern['IPv6'] = $pattern;
869:         }
870:         if (!isset(self::$_pattern['IPv4'])) {
871:             $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])';
872:             self::$_pattern['IPv4'] = $pattern;
873:         }
874:     }
875: 
876: /**
877:  * Reset internal variables for another validation run.
878:  *
879:  * @return void
880:  */
881:     protected static function _reset() {
882:         self::$errors = array();
883:     }
884: 
885: }
886: 
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