-
-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathvalidators.texy
More file actions
315 lines (227 loc) · 11.1 KB
/
validators.texy
File metadata and controls
315 lines (227 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
Value Validators
****************
.[perex]
Need to quickly and easily verify that a variable contains, for example, a valid email address? Then [api:Nette\Utils\Validators] will come in handy, a static class with useful functions for validating values.
Installation:
```shell
composer require nette/utils
```
All examples assume the following class alias is defined:
```php
use Nette\Utils\Validators;
```
Basic Usage
===========
The `Validators` class provides numerous methods for checking values, such as [#isUnicode()], [#isEmail()], [#isUrl()], etc., for use in your code:
```php
if (!Validators::isEmail($email)) {
throw new InvalidArgumentException('Invalid email address provided.');
}
```
Furthermore, it can verify whether the value satisfies the so-called [#expected types], which is a string where the individual options are separated by a vertical bar `|`. This makes it easy to verify union types using [#is()]:
```php
if (!Validators::is($val, 'int|string|bool')) {
// Handle invalid type...
}
```
This also allows you to create systems where expectations need to be written as strings (e.g., in annotations or configurations) and then validate values against them.
You can also declare an [assertion |#assert], which throws an exception if the expectation is not met.
Expected Types
==============
Expected types form a string consisting of one or more variants separated by a pipe `|`, similar to how types are written in PHP (e.g., `'int|string|bool'`). Nullable notation `?int` is also accepted.
An array where all elements are of a certain type is written in the form `int[]`.
Some types can be followed by a colon and a length `:length` or a range `:[min]..[max]`, e.g., `string:10` (a string of 10 bytes length), `float:10..` (a number 10 or greater), `array:..10` (an array with up to ten elements), or `list:10..20` (a list with 10 to 20 elements), or a regular expression like `pattern:[0-9]+`.
Overview of types and rules:
.[wide]
| PHP types ||
|--------------------------
| `array` .{width: 140px} | range for the number of elements can be specified
| `bool` |
| `float` | range for the value can be specified
| `int` | range for the value can be specified
| `null` |
| `object` |
| `resource` |
| `scalar` | `int|float|bool|string`
| `string` | range for the length in bytes can be specified
| `callable` |
| `iterable` |
| `mixed` |
|------------------------------------------------
| Pseudo-types ||
|------------------------------------------------
| `list` | indexed array, range for the number of elements can be specified
| `none` | empty value: `''`, `null`, `false`, `0`, `0.0`, `[]`
| `number` | `int|float`
| `numeric` | [number including string representation |#isNumeric]
| `numericint`| [integer including string representation |#isNumericInt]
| `unicode` | [UTF-8 string |#isUnicode], range for the length in characters can be specified
|------------------------------------------------
| Character class (must not be an empty string) ||
|------------------------------------------------
| `alnum` | all characters are alphanumeric
| `alpha` | all characters are letters `[A-Za-z]`
| `digit` | all characters are digits
| `lower` | all characters are lowercase letters `[a-z]`
| `space` | all characters are whitespace
| `upper` | all characters are uppercase letters `[A-Z]`
| `xdigit` | all characters are hexadecimal digits `[0-9A-Fa-f]`
|------------------------------------------------
| Syntax validation ||
|------------------------------------------------
| `pattern` | a regular expression that the **entire** string must match
| `email` | [Email |#isEmail]
| `identifier`| [PHP identifier |#isPhpIdentifier]
| `url` | [URL |#isUrl]
| `uri` | [URI |#isUri]
|------------------------------------------------
| Environment validation ||
|------------------------------------------------
| `class` | is an existing class name
| `interface` | is an existing interface name
| `directory` | is an existing directory path
| `file` | is an existing file path
Assertion
=========
assert($value, string $expected, string $label='variable'): void .[method]
--------------------------------------------------------------------------
Verifies that the value is one of the [#expected types] separated by a pipe. If not, it throws an [api:Nette\Utils\AssertionException]. The word `variable` in the exception message can be replaced by the `$label` parameter.
```php
Validators::assert('Nette', 'string:5'); // OK (string 'Nette' has 5 bytes)
Validators::assert('Lorem ipsum dolor sit', 'string:78');
// AssertionException: The variable expects to be string:78, string 'Lorem ipsum dolor sit' given.
```
assertField(array $array, string|int $key, ?string $expected=null, ?string $label=null): void .[method]
-------------------------------------------------------------------------------------------------------
Verifies that the element with key `$key` in array `$array` is one of the [#expected types] separated by a pipe. If not, it throws an [api:Nette\Utils\AssertionException]. The string `item '%' in array` in the exception message can be replaced by the `$label` parameter.
```php
$arr = ['foo' => 'Nette'];
Validators::assertField($arr, 'foo', 'string:5'); // OK
Validators::assertField($arr, 'bar', 'string:15');
// AssertionException: Missing item 'bar' in array.
Validators::assertField($arr, 'foo', 'int');
// AssertionException: The item 'foo' in array expects to be int, string 'Nette' given.
```
Validators
==========
is($value, string $expected): bool .[method]
--------------------------------------------
Checks if the value is one of the [#expected types] separated by a pipe.
```php
Validators::is(1, 'int|float'); // true
Validators::is(23, 'int:0..10'); // false (23 is outside the range 0-10)
Validators::is('Nette Framework', 'string:15'); // true, length is 15 bytes
Validators::is('Nette Framework', 'string:8..'); // true
Validators::is('Nette Framework', 'string:30..40'); // false
```
isEmail(mixed $value): bool .[method]
-------------------------------------
Verifies that the value is a valid email address. It does not verify that the domain actually exists, only the syntax is verified. The function also accounts for future [TLDs|https://en.wikipedia.org/wiki/Top-level_domain], which may also be in unicode.
```php
Validators::isEmail('example@nette.org'); // true
Validators::isEmail('example@localhost'); // false
Validators::isEmail('nette'); // false
```
isInRange(mixed $value, array $range): bool .[method]
-----------------------------------------------------
Checks if the value is within the given range `[min, max]`, where the upper or lower bound can be omitted (`null`). Numbers, strings, and DateTime objects can be compared.
If both boundaries are missing (`[null, null]`) or the value is `null`, it returns `false`.
```php
Validators::isInRange(5, [0, 5]); // true
Validators::isInRange(23, [null, 5]); // false
Validators::isInRange(23, [5]); // true (equivalent to [5, null])
Validators::isInRange(1, [5]); // false
```
isNone(mixed $value): bool .[method]
------------------------------------
Checks if the value is `0`, `''`, `false`, `null`, `0.0` or `[]`.
```php
Validators::isNone(0); // true
Validators::isNone(''); // true
Validators::isNone(false); // true
Validators::isNone(null); // true
Validators::isNone('nette'); // false
```
isNumeric(mixed $value): bool .[method]
---------------------------------------
Checks if the value is a number or a number represented as a string.
```php
Validators::isNumeric(23); // true
Validators::isNumeric(1.78); // true
Validators::isNumeric('+42'); // true
Validators::isNumeric('3.14'); // true
Validators::isNumeric('nette'); // false
Validators::isNumeric('1e6'); // false (scientific notation not accepted)
```
isNumericInt(mixed $value): bool .[method]
------------------------------------------
Checks if the value is an integer or an integer represented as a string.
```php
Validators::isNumericInt(23); // true
Validators::isNumericInt(1.78); // false
Validators::isNumericInt('+42'); // true
Validators::isNumericInt('3.14'); // false
Validators::isNumericInt('nette'); // false
```
isPhpIdentifier(string $value): bool .[method]
----------------------------------------------
Checks if the value is a syntactically valid identifier in PHP (e.g., for class names, method names, function names, etc.).
```php
Validators::isPhpIdentifier(''); // false
Validators::isPhpIdentifier('Hello1'); // true
Validators::isPhpIdentifier('1Hello'); // false
Validators::isPhpIdentifier('one two'); // false
```
isBuiltinType(string $type): bool .[method]
-------------------------------------------
Determines if `$type` is a PHP built-in type (e.g., `string`, `int`, `array`, `bool`). Otherwise, it's assumed to be a class name.
```php
Validators::isBuiltinType('string'); // true
Validators::isBuiltinType('Foo'); // false
```
isTypeDeclaration(string $type): bool .[method]
-----------------------------------------------
Checks whether the given type declaration string is syntactically valid according to PHP's type declaration rules (including union, intersection, DNF types).
```php
Validators::isTypeDeclaration('?string'); // true
Validators::isTypeDeclaration('string|null'); // true
Validators::isTypeDeclaration('Foo&Bar'); // true
Validators::isTypeDeclaration('(A&C)|null'); // true
Validators::isTypeDeclaration('?string|null'); // false
Validators::isTypeDeclaration('|foo'); // false
Validators::isTypeDeclaration('(A|B)'); // false
```
isClassKeyword(string $type): bool .[method]
--------------------------------------------
Determines if `$type` is one of the internal type keywords `self`, `parent`, or `static`.
```php
Validators::isClassKeyword('self'); // true
Validators::isClassKeyword('Foo'); // false
```
isUnicode(mixed $value): bool .[method]
---------------------------------------
Checks if the value is a valid UTF-8 string.
```php
Validators::isUnicode('nette'); // true
Validators::isUnicode(''); // true
Validators::isUnicode("\xA0"); // false (invalid UTF-8 sequence)
```
isUrl(mixed $value): bool .[method]
-----------------------------------
Checks if the value is a valid absolute URL address according to RFC 3986.
```php
Validators::isUrl('https://nette.org:8080/path?query#fragment'); // true
Validators::isUrl('http://localhost'); // true
Validators::isUrl('http://192.168.1.1'); // true
Validators::isUrl('http://[::1]'); // true
Validators::isUrl('http://user:pass@nette.org'); // false (userinfo part not validated by this function)
Validators::isUrl('nette.org'); // false (missing scheme)
```
isUri(string $value): bool .[method]
------------------------------------
Verifies that the value is a valid URI address, meaning it's a string starting with a syntactically valid scheme followed by a colon (e.g., `http:`, `https:`, `mailto:`, `ftp:`).
```php
Validators::isUri('https://nette.org'); // true
Validators::isUri('mailto:gandalf@example.org'); // true
Validators::isUri('nette.org'); // false (missing scheme)
```