Value Validators
Need to quickly and easily verify that a variable contains for example a valid email address? Then Nette\Utils\Validators will come in handy, a static class with useful functions for validating values.
Installation:
composer require nette/utils
All examples assume the following class alias is defined:
use Nette\Utils\Validators;
Basic Usage
The class Validators
has a number of methods for validating values, such as isList(), isUnicode(), isEmail(), isUrl(), etc. for use in
your code:
if (!Validators::isEmail($email)) {
throw new InvalidArgumentException;
}
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 if():
if (!Validators::is($val, 'int|string|bool')) {
// ...
}
But it also gives you the opportunity to create a system where it is necessary to write expectation as strings (for example in annotations or configuration) and then verify according to them.
You can also declare assertion, which throws an exception if is not met.
Expected Types
An expected types is a string consisting of one or more variants separated by a vertical bar |
, similar to writing
types in PHP (ie. 'int|string|bool')
. Nullable notation is also allowed ?int
.
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 the length :length
or the range :[min]..[max]
, eg
string:10
(a string with a length of 10 bytes), float:10..
(number 10 and bigger),
array:..10
(array of up to ten elements) or list:10..20
(list with 10 to 20 elements), or a regular
expression for pattern:[0-9]+
.
Overview of types and rules:
PHP types | |
---|---|
array |
range for the number of items can be given |
bool |
|
float |
range for the value can be given |
int |
range for the value can be given |
null |
|
object |
|
resource |
|
scalar |
int|float|bool|string |
string |
range for the length in bytes can be given |
callable |
|
iterable |
|
mixed |
|
pseudo-types | |
list |
indexed array, range for the number of items can be given |
none |
empty value: '' , null , false |
number |
int|float |
numeric |
number including textual representation |
numericint |
integer including textual representation |
unicode |
UTF-8 string, range for the length in characters can be given |
character class (cannot 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 spaces |
upper |
all characters are uppercase letters [A-Z] |
xdigit |
all characters are hexadecimal digits [0-9A-Fa-f] |
syntax validation | |
pattern |
a regular expression which the entire string must match |
email |
|
identifier |
PHP identifier |
url |
URL |
uri |
URI |
environment validation | |
class |
is existing class |
interface |
is existing interface |
directory |
is existing directory |
file |
is existing file |
Assertion
assert($value, string $expected, string
$label='variable'
): void
Verifies that the value is of expected types separated by pipe. If not, it throws exception
Nette\Utils\AssertionException. The word
variable
in the exception message can be replaced by parameter $label
.
Validators::assert('Nette', 'string:5'); // OK
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
Verifies that element $key
in array $array
is of expected types
separated by pipe. If not, it throws exception Nette\Utils\AssertionException. The string
item '%' in array
in the exception message can be replaced by parameter $label
.
$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
Checks if the value is of expected types separated by pipe.
Validators::is(1, 'int|float'); // true
Validators::is(23, 'int:0..10'); // false
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
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 counts on future TLDs, which may also be in unicode.
Validators::isEmail('example@nette.org'); // true
Validators::isEmail('example@localhost'); // false
Validators::isEmail('nette'); // false
isInRange(mixed $value, array $range): bool
Checks if the value is in the given range [min, max]
, where the upper or lower limit 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
.
Validators::isInRange(5, [0, 5]); // true
Validators::isInRange(23, [null, 5]); // false
Validators::isInRange(23, [5]); // true
Validators::isInRange(1, [5]); // false
isNone(mixed $value): bool
Checks if the value is 0
, ''
, false
or null
.
Validators::isNone(0); // true
Validators::isNone(''); // true
Validators::isNone(false); // true
Validators::isNone(null); // true
Validators::isNone('nette'); // false
isNumeric(mixed $value): bool
Checks if the value is a number or a number written in a string.
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
isNumericInt(mixed $value): bool
Checks if the value is an integer or a integer written in a string.
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
Checks if the value is a syntactically valid identifier in PHP, for example for names of classes, methods, functions, etc.
Validators::isPhpIdentifier(''); // false
Validators::isPhpIdentifier('Hello1'); // true
Validators::isPhpIdentifier('1Hello'); // false
Validators::isPhpIdentifier('one two'); // false
isBuiltinType(string $type): bool
Determines if $type
is PHP built-in type. Otherwise, it is the class name.
Validators::isBuiltinType('string'); // true
Validators::isBuiltinType('Foo'); // false
isTypeDeclaration(string $type): bool
Checks whether the type declaration is syntactically correct.
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
Determine if $type
is one of the internal types self
, parent
, static
.
Validators::isClassKeyword('self'); // true
Validators::isClassKeyword('Foo'); // false
isUnicode(mixed $value): bool
Checks if the value is a valid UTF-8 string.
Validators::isUnicode('nette'); // true
Validators::isUnicode(''); // true
Validators::isUnicode("\xA0"); // false
isUrl(mixed $value): bool
Checks if the value is a valid URL address.
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
Validators::isUrl('nette.org'); // false
isUri(string $value): bool
Verifies that the value is a valid URI address, that is, actually a string beginning with a syntactically valid schema.
Validators::isUri('https://nette.org'); // true
Validators::isUri('mailto:gandalf@example.org'); // true
Validators::isUri('nette.org'); // false