• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / forms / 28588025136

02 Jul 2026 11:28AM UTC coverage: 93.105% (+0.4%) from 92.701%
28588025136

push

github

dg
added Repeater example

2363 of 2538 relevant lines covered (93.1%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.03
/src/Forms/Validator.php
1
<?php declare(strict_types=1);
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
use function array_map, count, explode, filter_var, in_array, is_a, is_array, is_float, is_int, is_object, is_string, preg_replace, preg_replace_callback, rtrim, str_replace, strtolower;
14

15

16
/**
17
 * Common validators.
18
 */
19
final class Validator
20
{
21
        use Nette\StaticClass;
22

23
        /** @var array<string, string> */
24
        public static array $messages = [
25
                Form::Equal => 'Please enter %s.',
26
                Form::NotEqual => 'This value should not be %s.',
27
                Form::Filled => 'This field is required.',
28
                Form::Blank => 'This field should be blank.',
29
                Form::MinLength => 'Please enter at least %d characters.',
30
                Form::MaxLength => '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::Enum => 'Please select a valid option.',
35
                Form::Integer => 'Please enter a valid integer.',
36
                Form::Float => 'Please enter a valid number.',
37
                Form::Min => 'Please enter a value greater than or equal to %d.',
38
                Form::Max => 'Please enter a value less than or equal to %d.',
39
                Form::Range => 'Please enter a value between %d and %d.',
40
                Form::MaxFileSize => 'The size of the uploaded file can be up to %d bytes.',
41
                Form::MaxPostSize => 'The uploaded data exceeds the limit of %d bytes.',
42
                Form::MimeType => 'The uploaded file is not in the expected format.',
43
                Form::Image => 'The uploaded file must be image in format JPEG, GIF, PNG or WebP.',
44
                Controls\SelectBox::Valid => 'Please select a valid option.',
45
                Controls\UploadControl::Valid => 'An error occurred during file upload.',
46
                Repeater::MinItems => 'Please add at least %d items.',
47
                Repeater::MaxItems => 'Please add no more than %d items.',
48
        ];
49

50

51
        /**
52
         * @internal
53
         */
54
        public static function formatMessage(Rule $rule, bool $withValue = true): string|Nette\HtmlStringable
1✔
55
        {
56
                $message = $rule->message;
1✔
57
                if ($message instanceof Nette\HtmlStringable) {
1✔
58
                        return $message;
×
59

60
                } elseif ($message === null && is_string($rule->validator) && isset(static::$messages[$rule->validator])) {
1✔
61
                        $message = static::$messages[$rule->validator];
1✔
62

63
                } elseif ($message == null) { // intentionally ==
1✔
64
                        trigger_error(
×
65
                                "Missing validation message for control '{$rule->control->getName()}'"
×
66
                                . (is_string($rule->validator) ? " (validator '{$rule->validator}')." : '.'),
×
67
                                E_USER_WARNING,
×
68
                        );
69
                }
70

71
                if ($translator = $rule->control->getForm()->getTranslator()) {
1✔
72
                        $message = $translator->translate($message, is_int($rule->arg) ? $rule->arg : null);
1✔
73
                }
74

75
                $message = preg_replace_callback('#%(name|label|value|\d+\$[ds]|[ds])#', function (array $m) use ($rule, $withValue, $translator) {
1✔
76
                        static $i = -1;
1✔
77
                        switch ($m[1]) {
1✔
78
                                case 'name': return $rule->control->getName();
1✔
79
                                case 'label':
80
                                        if ($rule->control instanceof Controls\BaseControl) {
1✔
81
                                                $caption = $rule->control->getCaption();
1✔
82
                                                $caption = match (true) {
1✔
83
                                                        $caption instanceof Nette\Utils\Html => $caption->getText(),
1✔
84
                                                        $caption instanceof Nette\HtmlStringable => (string) $caption,
1✔
85
                                                        $translator !== null => $translator->translate($caption),
1✔
86
                                                        default => $caption,
1✔
87
                                                };
88
                                                return rtrim((string) $caption, ':');
1✔
89
                                        }
90

91
                                        return '';
92
                                case 'value': return $withValue
1✔
93
                                                ? $rule->control->getValue()
1✔
94
                                                : $m[0];
1✔
95
                                default:
96
                                        $args = is_array($rule->arg) ? $rule->arg : [$rule->arg];
1✔
97
                                        $i = (int) $m[1] ? (int) $m[1] - 1 : $i + 1;
1✔
98
                                        $arg = $args[$i] ?? null;
1✔
99
                                        if ($arg === null) {
1✔
100
                                                return '';
1✔
101
                                        } elseif ($arg instanceof Control) {
1✔
102
                                                return $withValue ? $args[$i]->getValue() : "%$i";
1✔
103
                                        } elseif ($rule->control instanceof Controls\DateTimeControl) {
1✔
104
                                                return $rule->control->formatLocaleText($arg);
1✔
105
                                        } else {
106
                                                return $arg;
1✔
107
                                        }
108
                        }
109
                }, $message);
1✔
110
                return $message;
1✔
111
        }
112

113

114
        /********************* default validators ****************d*g**/
115

116

117
        /**
118
         * Checks whether the control's value equals the argument (string comparison, supports arrays).
119
         */
120
        public static function validateEqual(Control $control, mixed $arg): bool
1✔
121
        {
122
                $value = $control->getValue();
1✔
123
                $values = is_array($value) ? $value : [$value];
1✔
124
                $args = is_array($arg) ? $arg : [$arg];
1✔
125

126
                foreach ($values as $val) {
1✔
127
                        foreach ($args as $item) {
1✔
128
                                if ($item instanceof \BackedEnum) {
1✔
129
                                        $item = $item->value;
1✔
130
                                }
131

132
                                if ((string) $val === (string) $item) {
1✔
133
                                        continue 2;
1✔
134
                                }
135
                        }
136

137
                        return false;
1✔
138
                }
139

140
                return (bool) $values;
1✔
141
        }
142

143

144
        /**
145
         * Checks whether the control's value does not equal the argument.
146
         */
147
        public static function validateNotEqual(Control $control, mixed $arg): bool
1✔
148
        {
149
                return !static::validateEqual($control, $arg);
1✔
150
        }
151

152

153
        /**
154
         * Always returns the argument value, used for static (constant) conditions.
155
         */
156
        public static function validateStatic(Control $control, bool $arg): bool
1✔
157
        {
158
                return $arg;
1✔
159
        }
160

161

162
        /**
163
         * Checks whether the control is filled.
164
         */
165
        public static function validateFilled(Controls\BaseControl $control): bool
1✔
166
        {
167
                return $control->isFilled();
1✔
168
        }
169

170

171
        /**
172
         * Checks whether the control is not filled.
173
         */
174
        public static function validateBlank(Controls\BaseControl $control): bool
1✔
175
        {
176
                return !$control->isFilled();
1✔
177
        }
178

179

180
        /**
181
         * Checks whether the control passes all its validation rules (used in conditions).
182
         */
183
        public static function validateValid(Controls\BaseControl $control): bool
1✔
184
        {
185
                return $control->getRules()->validate();
1✔
186
        }
187

188

189
        /**
190
         * Checks whether the control's value falls within the specified range (inclusive).
191
         * @param  array{int|float|string|\DateTimeInterface|null, int|float|string|\DateTimeInterface|null}  $range
192
         */
193
        public static function validateRange(Control $control, array $range): bool
1✔
194
        {
195
                if ($control instanceof Controls\DateTimeControl) {
1✔
196
                        return $control->validateMinMax($range[0] ?? null, $range[1] ?? null);
1✔
197
                }
198
                $range = array_map(fn($v) => $v === '' ? null : $v, $range);
1✔
199
                return Validators::isInRange($control->getValue(), $range);
1✔
200
        }
201

202

203
        /**
204
         * Checks whether the control's value is greater than or equal to the minimum.
205
         */
206
        public static function validateMin(Control $control, int|float|string|\DateTimeInterface $minimum): bool
1✔
207
        {
208
                return Validators::isInRange($control->getValue(), [$minimum === '' ? null : $minimum, null]);
1✔
209
        }
210

211

212
        /**
213
         * Checks whether the control's value is less than or equal to the maximum.
214
         */
215
        public static function validateMax(Control $control, int|float|string|\DateTimeInterface $maximum): bool
1✔
216
        {
217
                return Validators::isInRange($control->getValue(), [null, $maximum === '' ? null : $maximum]);
1✔
218
        }
219

220

221
        /**
222
         * Checks whether the string length or array count falls within the given range [min, max].
223
         * @param  array{?int, ?int}|int  $range
224
         */
225
        public static function validateLength(Control $control, array|int $range): bool
1✔
226
        {
227
                if (!is_array($range)) {
1✔
228
                        $range = [$range, $range];
1✔
229
                }
230

231
                $value = $control->getValue();
1✔
232
                return Validators::isInRange(is_array($value) ? count($value) : Strings::length((string) $value), $range);
1✔
233
        }
234

235

236
        /**
237
         * Checks whether the string length or array count is at least the specified minimum.
238
         */
239
        public static function validateMinLength(Control $control, int $length): bool
1✔
240
        {
241
                return static::validateLength($control, [$length, null]);
1✔
242
        }
243

244

245
        /**
246
         * Checks whether the string length or array count does not exceed the specified maximum.
247
         */
248
        public static function validateMaxLength(Control $control, int $length): bool
1✔
249
        {
250
                return static::validateLength($control, [null, $length]);
1✔
251
        }
252

253

254
        /**
255
         * Checks whether the submit button was used to submit the form.
256
         */
257
        public static function validateSubmitted(Controls\SubmitButton $control): bool
1✔
258
        {
259
                return $control->isSubmittedBy();
1✔
260
        }
261

262

263
        /**
264
         * Checks whether the control's value is a valid email address.
265
         */
266
        public static function validateEmail(Control $control): bool
1✔
267
        {
268
                return Validators::isEmail((string) $control->getValue());
1✔
269
        }
270

271

272
        /**
273
         * Checks whether the control's value is a valid URL. Auto-prepends 'https://' if the scheme is missing.
274
         */
275
        public static function validateUrl(Control $control): bool
1✔
276
        {
277
                $value = (string) $control->getValue();
1✔
278
                if (Validators::isUrl($value)) {
1✔
279
                        return true;
1✔
280
                }
281

282
                $value = "https://$value";
1✔
283
                if (Validators::isUrl($value)) {
1✔
284
                        $control->setValue($value);
1✔
285
                        return true;
1✔
286
                }
287

288
                return false;
1✔
289
        }
290

291

292
        /**
293
         * Checks whether the control's value matches the regular expression (anchored, case-sensitive by default).
294
         */
295
        public static function validatePattern(Control $control, string $pattern, bool $caseInsensitive = false): bool
1✔
296
        {
297
                $regexp = "\x01^(?:$pattern)$\x01Du" . ($caseInsensitive ? 'i' : '');
1✔
298
                foreach (static::toArray($control->getValue()) as $item) {
1✔
299
                        $value = $item instanceof Nette\Http\FileUpload ? $item->getUntrustedName() : $item;
1✔
300
                        if (!Strings::match((string) $value, $regexp)) {
1✔
301
                                return false;
1✔
302
                        }
303
                }
304

305
                return true;
1✔
306
        }
307

308

309
        public static function validatePatternCaseInsensitive(Control $control, string $pattern): bool
1✔
310
        {
311
                return self::validatePattern($control, $pattern, caseInsensitive: true);
1✔
312
        }
313

314

315
        /**
316
         * Checks whether the control's value is a valid case of the given backed enum.
317
         * @param  class-string  $enum  backed enum class
318
         */
319
        public static function validateEnum(Control $control, string $enum): bool
1✔
320
        {
321
                if (!is_a($enum, \BackedEnum::class, allow_string: true)) {
1✔
322
                        throw new Nette\InvalidArgumentException("The Enum validator requires a backed enum class, '$enum' given.");
1✔
323
                }
324

325
                $intBacked = (new \ReflectionEnum($enum))->getBackingType()?->getName() === 'int';
1✔
326
                foreach (static::toArray($control->getValue()) as $value) {
1✔
327
                        if ($intBacked) {
1✔
328
                                $value = filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
1✔
329
                                if ($value === null || $enum::tryFrom($value) === null) {
1✔
330
                                        return false;
1✔
331
                                }
332
                        } elseif (!is_string($value) || $enum::tryFrom($value) === null) {
1✔
333
                                return false;
1✔
334
                        }
335
                }
336

337
                return true;
1✔
338
        }
339

340

341
        /**
342
         * Checks whether the control's value is a non-negative integer string or int.
343
         */
344
        public static function validateNumeric(Control $control): bool
1✔
345
        {
346
                $value = $control->getValue();
1✔
347
                return (is_int($value) && $value >= 0)
1✔
348
                        || (is_string($value) && Strings::match($value, '#^\d+$#D'));
1✔
349
        }
350

351

352
        /**
353
         * Checks whether the control's value is an integer. Normalizes the value by casting it to int.
354
         */
355
        public static function validateInteger(Control $control): bool
1✔
356
        {
357
                if (
358
                        Validators::isNumericInt($value = $control->getValue())
1✔
359
                        && !is_float($tmp = $value * 1) // too big for int?
1✔
360
                ) {
361
                        $control->setValue($tmp);
1✔
362
                        return true;
1✔
363
                }
364

365
                return false;
1✔
366
        }
367

368

369
        /**
370
         * Checks whether the control's value is a number. Normalizes spaces and commas and casts it to float.
371
         */
372
        public static function validateFloat(Control $control): bool
1✔
373
        {
374
                $value = $control->getValue();
1✔
375
                if (is_string($value)) {
1✔
376
                        $value = str_replace([' ', ','], ['', '.'], $value);
1✔
377
                }
378

379
                if (Validators::isNumeric($value)) {
1✔
380
                        $control->setValue((float) $value);
1✔
381
                        return true;
1✔
382
                }
383

384
                return false;
1✔
385
        }
386

387

388
        /**
389
         * Checks whether all uploaded files are within the size limit (in bytes).
390
         */
391
        public static function validateFileSize(Controls\UploadControl $control, int $limit): bool
1✔
392
        {
393
                foreach (static::toArray($control->getValue()) as $file) {
1✔
394
                        if ($file->getSize() > $limit || $file->getError() === UPLOAD_ERR_INI_SIZE) {
1✔
395
                                return false;
1✔
396
                        }
397
                }
398

399
                return true;
1✔
400
        }
401

402

403
        /**
404
         * Checks whether all uploaded files match one of the allowed MIME types (wildcards like 'image/*' are supported).
405
         * @param  string|string[]  $mimeType
406
         */
407
        public static function validateMimeType(Controls\UploadControl $control, string|array $mimeType): bool
1✔
408
        {
409
                $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
1✔
410
                foreach (static::toArray($control->getValue()) as $file) {
1✔
411
                        $type = strtolower($file->getContentType() ?? '');
1✔
412
                        if (!in_array($type, $mimeTypes, true) && !in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, true)) {
1✔
413
                                return false;
1✔
414
                        }
415
                }
416

417
                return true;
1✔
418
        }
419

420

421
        /**
422
         * Checks whether all uploaded files are images (JPEG, PNG, GIF, WebP, AVIF).
423
         */
424
        public static function validateImage(Controls\UploadControl $control): bool
1✔
425
        {
426
                foreach (static::toArray($control->getValue()) as $file) {
1✔
427
                        if (!$file->isImage()) {
1✔
428
                                return false;
×
429
                        }
430
                }
431

432
                return true;
1✔
433
        }
434

435

436
        /** @return mixed[] */
437
        private static function toArray(mixed $value): array
1✔
438
        {
439
                return is_object($value) ? [$value] : (array) $value;
1✔
440
        }
441
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc