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 Validators class provides numerous methods for checking values, such as isUnicode(), isEmail(), isUrl(), etc., for use in your code:
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():
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, 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:
| PHP types | ||||
|---|---|---|---|---|
array | 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 | |||
numericint | integer including string representation | |||
unicode | UTF-8 string, 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 | ||||
identifier | PHP identifier | |||
url | URL | |||
uri | URI | |||
| 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
Verifies that the value is one of the expected types separated by a pipe. If not, it throws an Nette\Utils\AssertionException. The word variable in the exception message can be replaced by the $label parameter.
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
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 Nette\Utils\AssertionException. The string item '%' in array in the exception message can be replaced by the $label parameter.
$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 one of the expected types separated by a pipe.
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
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, 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 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.
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
Checks if the value is 0, '', false, null, 0.0 or [].
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 represented as 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 (scientific notation not accepted) isNumericInt (mixed $value): bool
Checks if the value is an integer or an integer represented as 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 (e.g., for class names, method names, function names, 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 a PHP built-in type (e.g., string, int, array, bool). Otherwise, it's assumed to be a class name.
Validators::isBuiltinType('string'); // true Validators::isBuiltinType('Foo'); // false isTypeDeclaration (string $type): bool
Checks whether the given type declaration string is syntactically valid according to PHP's type declaration rules (including union, intersection, DNF types).
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
Determines if $type is one of the internal type keywords self, parent, or 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 (invalid UTF-8 sequence) isUrl (mixed $value): bool
Checks if the value is a valid absolute URL address according to RFC 3986.
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
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:).
Validators::isUri('https://nette.org'); // true Validators::isUri('mailto:gandalf@example.org'); // true Validators::isUri('nette.org'); // false (missing scheme)