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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 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
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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