Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
      • Traits
    • Reflection
    • Security
    • Tokenizer
    • Utils
  • Tracy
    • Bridges
      • Nette
  • none

Classes

  • Container
  • ControlGroup
  • Form
  • Helpers
  • Rule
  • Rules
  • Validator

Interfaces

  • IControl
  • IFormRenderer
  • ISubmitterControl
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Forms;
  9: 
 10: use Nette;
 11: use Nette\Utils\Strings;
 12: use Nette\Utils\Validators;
 13: 
 14: 
 15: /**
 16:  * Common validators.
 17:  */
 18: class Validator
 19: {
 20:     use Nette\StaticClass;
 21: 
 22:     /** @var array */
 23:     public static $messages = [
 24:         Form::PROTECTION => 'Your session has expired. Please return to the home page and try again.',
 25:         Form::EQUAL => 'Please enter %s.',
 26:         Form::NOT_EQUAL => 'This value should not be %s.',
 27:         Form::FILLED => 'This field is required.',
 28:         Form::BLANK => 'This field should be blank.',
 29:         Form::MIN_LENGTH => 'Please enter at least %d characters.',
 30:         Form::MAX_LENGTH => 'Please enter no more than %d characters.',
 31:         Form::LENGTH => 'Please enter a value between %d and %d characters long.',
 32:         Form::EMAIL => 'Please enter a valid email address.',
 33:         Form::URL => 'Please enter a valid URL.',
 34:         Form::INTEGER => 'Please enter a valid integer.',
 35:         Form::FLOAT => 'Please enter a valid number.',
 36:         Form::MIN => 'Please enter a value greater than or equal to %d.',
 37:         Form::MAX => 'Please enter a value less than or equal to %d.',
 38:         Form::RANGE => 'Please enter a value between %d and %d.',
 39:         Form::MAX_FILE_SIZE => 'The size of the uploaded file can be up to %d bytes.',
 40:         Form::MAX_POST_SIZE => 'The uploaded data exceeds the limit of %d bytes.',
 41:         Form::MIME_TYPE => 'The uploaded file is not in the expected format.',
 42:         Form::IMAGE => 'The uploaded file must be image in format JPEG, GIF or PNG.',
 43:         Controls\SelectBox::VALID => 'Please select a valid option.',
 44:         Controls\UploadControl::VALID => 'An error occurred during file upload.',
 45:     ];
 46: 
 47: 
 48:     /** @internal */
 49:     public static function formatMessage(Rule $rule, $withValue = true)
 50:     {
 51:         $message = $rule->message;
 52:         if ($message instanceof Nette\Utils\IHtmlString) {
 53:             return $message;
 54: 
 55:         } elseif ($message === null && is_string($rule->validator) && isset(static::$messages[$rule->validator])) {
 56:             $message = static::$messages[$rule->validator];
 57: 
 58:         } elseif ($message == null) { // intentionally ==
 59:             trigger_error("Missing validation message for control '{$rule->control->getName()}'.", E_USER_WARNING);
 60:         }
 61: 
 62:         if ($translator = $rule->control->getForm()->getTranslator()) {
 63:             $message = $translator->translate($message, is_int($rule->arg) ? $rule->arg : null);
 64:         }
 65: 
 66:         $message = preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#', function ($m) use ($rule, $withValue) {
 67:             static $i = -1;
 68:             switch ($m[1]) {
 69:                 case 'name': return $rule->control->getName();
 70:                 case 'label': return $rule->control instanceof Controls\BaseControl
 71:                     ? rtrim($rule->control->translate($rule->control->caption), ':')
 72:                     : null;
 73:                 case 'value': return $withValue ? $rule->control->getValue() : $m[0];
 74:                 default:
 75:                     $args = is_array($rule->arg) ? $rule->arg : [$rule->arg];
 76:                     $i = (int) $m[1] ? (int) $m[1] - 1 : $i + 1;
 77:                     return isset($args[$i]) ? ($args[$i] instanceof IControl ? ($withValue ? $args[$i]->getValue() : "%$i") : $args[$i]) : '';
 78:             }
 79:         }, $message);
 80:         return $message;
 81:     }
 82: 
 83: 
 84:     /********************* default validators ****************d*g**/
 85: 
 86: 
 87:     /**
 88:      * Is control's value equal with second parameter?
 89:      * @return bool
 90:      */
 91:     public static function validateEqual(IControl $control, $arg)
 92:     {
 93:         $value = $control->getValue();
 94:         foreach ((is_array($value) ? $value : [$value]) as $val) {
 95:             foreach ((is_array($arg) ? $arg : [$arg]) as $item) {
 96:                 if ((string) $val === (string) $item) {
 97:                     continue 2;
 98:                 }
 99:             }
100:             return false;
101:         }
102:         return true;
103:     }
104: 
105: 
106:     /**
107:      * Is control's value not equal with second parameter?
108:      * @return bool
109:      */
110:     public static function validateNotEqual(IControl $control, $arg)
111:     {
112:         return !static::validateEqual($control, $arg);
113:     }
114: 
115: 
116:     /**
117:      * Returns argument.
118:      * @return bool
119:      */
120:     public static function validateStatic(IControl $control, $arg)
121:     {
122:         return $arg;
123:     }
124: 
125: 
126:     /**
127:      * Is control filled?
128:      * @return bool
129:      */
130:     public static function validateFilled(IControl $control)
131:     {
132:         return $control->isFilled();
133:     }
134: 
135: 
136:     /**
137:      * Is control not filled?
138:      * @return bool
139:      */
140:     public static function validateBlank(IControl $control)
141:     {
142:         return !$control->isFilled();
143:     }
144: 
145: 
146:     /**
147:      * Is control valid?
148:      * @return bool
149:      */
150:     public static function validateValid(Controls\BaseControl $control)
151:     {
152:         return $control->getRules()->validate();
153:     }
154: 
155: 
156:     /**
157:      * Is a control's value number in specified range?
158:      * @param  IControl
159:      * @param  array
160:      * @return bool
161:      */
162:     public static function validateRange(IControl $control, $range)
163:     {
164:         $range = array_map(function ($v) {
165:             return $v === '' ? null : $v;
166:         }, $range);
167:         return Validators::isInRange($control->getValue(), $range);
168:     }
169: 
170: 
171:     /**
172:      * Is a control's value number greater than or equal to the specified minimum?
173:      * @param  IControl
174:      * @param  float
175:      * @return bool
176:      */
177:     public static function validateMin(IControl $control, $minimum)
178:     {
179:         return Validators::isInRange($control->getValue(), [$minimum === '' ? null : $minimum, null]);
180:     }
181: 
182: 
183:     /**
184:      * Is a control's value number less than or equal to the specified maximum?
185:      * @param  IControl
186:      * @param  float
187:      * @return bool
188:      */
189:     public static function validateMax(IControl $control, $maximum)
190:     {
191:         return Validators::isInRange($control->getValue(), [null, $maximum === '' ? null : $maximum]);
192:     }
193: 
194: 
195:     /**
196:      * Count/length validator. Range is array, min and max length pair.
197:      * @param  IControl
198:      * @param  array|int
199:      * @return bool
200:      */
201:     public static function validateLength(IControl $control, $range)
202:     {
203:         if (!is_array($range)) {
204:             $range = [$range, $range];
205:         }
206:         $value = $control->getValue();
207:         return Validators::isInRange(is_array($value) ? count($value) : Strings::length((string) $value), $range);
208:     }
209: 
210: 
211:     /**
212:      * Has control's value minimal count/length?
213:      * @param  IControl
214:      * @param  int
215:      * @return bool
216:      */
217:     public static function validateMinLength(IControl $control, $length)
218:     {
219:         return static::validateLength($control, [$length, null]);
220:     }
221: 
222: 
223:     /**
224:      * Is control's value count/length in limit?
225:      * @param  IControl
226:      * @param  int
227:      * @return bool
228:      */
229:     public static function validateMaxLength(IControl $control, $length)
230:     {
231:         return static::validateLength($control, [null, $length]);
232:     }
233: 
234: 
235:     /**
236:      * Has been button pressed?
237:      * @return bool
238:      */
239:     public static function validateSubmitted(Controls\SubmitButton $control)
240:     {
241:         return $control->isSubmittedBy();
242:     }
243: 
244: 
245:     /**
246:      * Is control's value valid email address?
247:      * @return bool
248:      */
249:     public static function validateEmail(IControl $control)
250:     {
251:         return Validators::isEmail($control->getValue());
252:     }
253: 
254: 
255:     /**
256:      * Is control's value valid URL?
257:      * @return bool
258:      */
259:     public static function validateUrl(IControl $control)
260:     {
261:         if (Validators::isUrl($value = $control->getValue())) {
262:             return true;
263: 
264:         } elseif (Validators::isUrl($value = "http://$value")) {
265:             $control->setValue($value);
266:             return true;
267:         }
268:         return false;
269:     }
270: 
271: 
272:     /**
273:      * Does the control's value match the regular expression?
274:      * Case-sensitive to comply with the HTML5 <input /> pattern attribute behaviour
275:      * @param  string
276:      * @return bool
277:      */
278:     public static function validatePattern(IControl $control, $pattern, $caseInsensitive = false)
279:     {
280:         $regexp = "\x01^(?:$pattern)\\z\x01u" . ($caseInsensitive ? 'i' : '');
281:         foreach (static::toArray($control->getValue()) as $item) {
282:             $value = $item instanceof Nette\Http\FileUpload ? $item->getName() : $item;
283:             if (!Strings::match($value, $regexp)) {
284:                 return false;
285:             }
286:         }
287:         return true;
288:     }
289: 
290: 
291:     public static function validatePatternCaseInsensitive(IControl $control, $pattern)
292:     {
293:         return self::validatePattern($control, $pattern, true);
294:     }
295: 
296: 
297:     /**
298:      * Is a control's value decimal number?
299:      * @return bool
300:      */
301:     public static function validateInteger(IControl $control)
302:     {
303:         if (Validators::isNumericInt($value = $control->getValue())) {
304:             if (!is_float($tmp = $value * 1)) { // bigint leave as string
305:                 $control->setValue($tmp);
306:             }
307:             return true;
308:         }
309:         return false;
310:     }
311: 
312: 
313:     /**
314:      * Is a control's value float number?
315:      * @return bool
316:      */
317:     public static function validateFloat(IControl $control)
318:     {
319:         $value = str_replace([' ', ','], ['', '.'], $control->getValue());
320:         if (Validators::isNumeric($value)) {
321:             $control->setValue((float) $value);
322:             return true;
323:         }
324:         return false;
325:     }
326: 
327: 
328:     /**
329:      * Is file size in limit?
330:      * @param  int
331:      * @return bool
332:      */
333:     public static function validateFileSize(Controls\UploadControl $control, $limit)
334:     {
335:         foreach (static::toArray($control->getValue()) as $file) {
336:             if ($file->getSize() > $limit || $file->getError() === UPLOAD_ERR_INI_SIZE) {
337:                 return false;
338:             }
339:         }
340:         return true;
341:     }
342: 
343: 
344:     /**
345:      * Has file specified mime type?
346:      * @param  IControl
347:      * @param  string|string[]
348:      * @return bool
349:      */
350:     public static function validateMimeType(Controls\UploadControl $control, $mimeType)
351:     {
352:         $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
353:         foreach (static::toArray($control->getValue()) as $file) {
354:             $type = strtolower($file->getContentType());
355:             if (!in_array($type, $mimeTypes, true) && !in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, true)) {
356:                 return false;
357:             }
358:         }
359:         return true;
360:     }
361: 
362: 
363:     /**
364:      * Is file image?
365:      * @return bool
366:      */
367:     public static function validateImage(Controls\UploadControl $control)
368:     {
369:         foreach (static::toArray($control->getValue()) as $file) {
370:             if (!$file->isImage()) {
371:                 return false;
372:             }
373:         }
374:         return true;
375:     }
376: 
377: 
378:     /**
379:      * @return array
380:      */
381:     private static function toArray($value)
382:     {
383:         return $value instanceof Nette\Http\FileUpload ? [$value] : (array) $value;
384:     }
385: }
386: 
Nette 2.4-20191120 API API documentation generated by ApiGen 2.8.0