Rules - rlanvin/php-form GitHub Wiki
- Internal type rules
- Type rules
- Value rules
- Special rules
These rules validate the internal type of the parameter, i.e. the type of the variable itself. For normal HTML form validation, they are not that useful, since everything is either a string or an array.
Check if the value is either null
, an empty string or an empty array. This rule differs from PHP's is_empty
in that 0 is not considered empty.
- Parameter: none
Check if the value is an array.
- Parameter: none
When using this validator, keep in mind that the final value after validation might or might not be an array. Therefore, you should always test the type of the value before using it as an array, otherwise you might get PHP errors such as "expected an array, string given".
For more control over validating array of values, check the special rule each
.
Check if the value is a string.
- Parameter: none
These rules check the type of the value that have been submitted, independantly of the type of the variable itself.
Check if the value is a boolean. The following values are considered a boolean:
'true', 't', 'yes', 'y', 'on', '1', 1, true // true
'false', 'f', 'no', 'n', 'off', '0', 0, false // false
- Parameter: sanitizing option (optional) (version >= 2.0)
By default, this rule will only sanitize string values.
So for example the strings 'false'
, 'f'
, 'no'
, 'n'
and 'off'
will be converted to the string '0'
, but the integer 0
and the boolean false
will not be modified and retain their type.
Value | Description |
---|---|
true (default) |
sanitize only strings |
false |
do not sanitize (value remains the original) |
'bool' |
sanitize and cast everything to a boolean |
'int' |
sanitize and cast everything to an int |
'string' |
sanitize and cast everything to a string |
Check if the value is a valid date representation.
- Parameter: Date format expected (default is
Y-m-d
) ornull
orfalse
to accept any valid date format (not recommended). (version >= 2.0)
(version >= 2.0)
Check if the value is a datetime expression. Shortcut for date
.
[`datetime`]
// is the same as:
['date' => 'Y-m-d H:i:s']
Check if the value is a time. Shortcut for date
.
[`time`]
// is the same as:
['date' => 'H:i']
Check if the value is a number or a numeric string, that is an integer or a float. This rule is not recommended as it is very loose, and you should consider using one of the following: integer
, intl_integer
, decimal
or intl_decimal
instead.
- Parameter: None
(version >= 2.0)
Check if the value is an integer number. Number with fractional parts (decimal) and/or thousands separators will be rejected. For example 1000
will be accepted, but 1 000
or 1,000
will not. For more localization options, check intl_integer
.
- Parameter: None
(version >= 2.0)
Check if the value is a decimal (a float). The decimal separator is optionnal, but must be "." (dot). Number with thousands separators will be rejected. For example 1234.56
will be accepted, but 1,234.56
will not. For more localization options, check intl_decimal
.
- Parameter: None
(version >= 2.0)
Check if the value is a integer number, using the intl
extension, and convert to int on success.
- Parameter: The locale (leave empty to use the current locale in the
Locale
class)
Example:
['intl_integer' => 'fr_FR']
// or, if the default locale is already fr_FR, you can just write:
['intl_integer']
// '1 000' and '1.000' are valid and will be converted to 1000
(version >= 2.0)
Check if the value is a decimal number, using the intl
extension. The format of the decimal number to expect is determined by the current locale.
- Parameter: The locale (leave empty to use the current locale in the
Locale
class)
Example:
['intl_decimal' => 'fr_FR']
// or, if the default locale is already fr_FR, you can just write:
['intl_decimal']
// '1.000,42' and '1 000,42' are valid and will be converted to 1000.42
Check if the value is a valid email address.
- Parameter: none
Note: This rule is based on PHP's filter_var
, and suffers from the same restrictions.
In general, this validates e-mail addresses against the syntax in RFC 822, with the exceptions that comments and whitespace folding are not supported.
Check if a value is a valid URL. It must begin with a protocol, but not necessarily http://
(ssh://
, 'mailto://` are also valid)
- Parameter: protocol(s) to check (default is to accept any protocol)
Example:
['url'] // will accept http://www.google.com and ssh://github.com
['url' => 'http'] // will only accept url starting with http
['url' => ['http','https']] // will only accept url starting with http or https
Note: This rule is based on PHP's filter_var
and suffers from the same restrictions, in particular when it comes to internationalized domain names.
Validates value as URL (according to RFC 2396. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto://. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.
(version >= 2.0)
Check if the value is a valid string representation of an IP address (IPv4 or IPv6).
- Parameter: a combination of constants from PHP's
filter_var
(optional)
Name | Description |
---|---|
FILTER_FLAG_IPV4 |
only IPv4 (see ipv4 ) |
FILTER_FLAG_IPV6 |
only IPv6 (see ipv6 ) |
FILTER_FLAG_NO_PRIV_RANGE |
not from private range |
FILTER_FLAG_NO_RES_RANGE |
not from reserver range |
Example:
['ip'] // validate any IPv4 or IPv6
['ip' => FILTER_FLAG_IPv4 | FILTER_FLAG_NO_PRIV_RANGE] // validate any public IPv4 (excluding private ranges)
(version >= 2.0)
Check if the value is a valid IPv4. Shortcut for ip
.
- Parameter: none
(version >= 2.0)
Check if the value is a valid IPv6. Shortcut for ip
.
- Parameter: none
Check if the value is in an array of values.
- Parameter: Array of allowed values (required)
Example:
['in' => array('foo','bar')]
// 'foo' => true
// 'foobar' => false
If the value itself is a array, this will check that all values of the array are in the array given as a parameter.
Example:
['in' => array('foo','bar')]
// ['foo','bar'] => true ('foo' and 'bar' are both allowed)
// ['foo', 'foobar'] => false ('foo' is allowed, but not 'foobar')
For more control over validating array of values, check the special rule each
.
Same as in
, excepts that it checks that the value is a key of the array. Consequently it also checks that the value can be used as a key (string
or int
type).
- Parameter: Associative array where the key is the allowed value (required).
Example:
['in_keys' => array(1 => 'Foo', 2 => 'Bar')]
// 1 => true
// 3 => false
// 'foo' => false
If the value itself is a array, this will check that all values of the array are keys of the array given as a parameter.
Example:
['in' => array(1 => 'Foo', 2 => 'Bar')]
// [1,2] => true
// [1,3] => false
// ['Foo','Bar'] => false
For more control over validating array of values, check the special rule each
.
(version >= 2.0)
Check if the value is between two values (inclusive). Works with any type that can be compared by PHP.
- Parameter: an array of exactly 2 values - minimum or
null
and maximum ornull
. (required)
Example:
['between' => [0,10]]
// 5 will pass
// 12 will not
['between' => [10,null]]
// 10 or anything greater than 10 will pass
['between' => ['2015-01-01','2015-01-31']]
// '2015-01-15' will pass
// '2016-01-15' will not
Note: while this rule works with any type, it is highly recommended to check the type first with one of the type rules, otherwise you might have unpleasant surprises due to PHP's loose type comparison.
(version >= 2.0)
Check if the value is greater or equal than a given value. Works with any type that can be compared by PHP.
- Parameter: the minimum value (required)
Example:
['min' => 10]
// 10 or anything greater than 10 will pass
(version >= 2.0)
Check if the value is less or equal than a given value. Works with any type that can be compared by PHP.
- Parameter: the maximum value (required)
['max' => 10]
// 10 or anything less than 10 will pass (including negative values)
(version >= 2.0)
Check if the length of the value is between two values (inclusive). Consequently, it also checks if the value is a string or can be converted to a string. This rule can validate UTF-8 strings and requires the mbstring
extension to be loaded and configured.
- Parameter: an array of exactly 2 values - minimum or
null
and maximum ornull
. (required)
Check if the length of the value is greater or equal than a given length. Consequently, it also checks if the value is a string or can be converted to a string.
This rule can validate UTF-8 strings and requires the mbstring
extension to be loaded and configured.
- Parameter: the length (required)
['min_length' => 10]
// 'hello' => false
// 'hello world' => true
Note: For this validator to have an effect, it must be paired with required
or with the option allow_empty => false
.
Check if the length of the value is less or equal than a given length.
This rule can validate UTF-8 strings and requires the mbstring
extension to be loaded and configured.
- Parameter: the length (required)
['max_length' => 10]
// 'hello' => true
// 'hello world' => false
Check if the value matches a regular expression
- Parameter: the regular expression (required).
Example:
['regexp' => "/^([\p{L}0-9\-_]+)$/u"]
// 'rémi-123' => true
// 'garbage !$' => false
Trim the value. This rule will always pass, even if the value cannot be trimmed (e.g. an array).
- Parameter: The character(s) that will be stripped (optional). Default is PHP's trim default.
Example:
['trim']
['trim' => " \t\n\r\0\x0B"]
The rule required
will check if a value is present.
The following values are considered empty and will fail the check:
-
''
(empty string) -
' '
(a string only made of space) null
-
array()
(empty array)
The following values are considered not empty and will pass check:
-
0
(integer zero - considered as a valid integer value) -
false
(boolean false - considered as a valid boolean value)
Important When the required
rule is not present, it will cause empty value to pass all validators by default. Validators such as min_length
will have no effect, and callbacks will not be called. You can change this behavior by setting allow_empty => false
in the options.
The rule each
will cause the validation to treat the value as an array, and validate each element of the array individually.
This rule will automatically cast the value to an array. Therefore, when using each
alone, you are guaranteed that the value at the end will be of type array, which is usually the desired behavior in a web application. However if you want to have a strict type validation (i.e. fail when the value is not an array, for example with an API), you must use the is_array
validator before each
.
This rule will also not run any validator on empty arrays. If you want to reject an empty array, you must use the required
validator before each
.
If you want to reject empty values inside the array, you must use the required
validator inside the each
validator.
Example #1:
HTML form:
<p><input type="input" name="tags[]" value=""></p>
<p><input type="input" name="tags[]" value=""></p>
<p><input type="input" name="tags[]" value=""></p>
PHP:
$form = new Form\Validator([
'tags' => ['each' => ['required', 'trim', 'min_length' => 2, 'max_length' => 16]]
]);
$form->validate($_POST);
This will check that each tag in the tags
array posted is not empty (required
), and is between 2 and 16 characters long after trimming.
Example #2: using each
instead of in
HTML form:
<p><label><input type="checkbox" name="colors[]" value="red"> Red</label></p>
<p><label><input type="checkbox" name="colors[]" value="blue"> Blue</label></p>
<p><label><input type="checkbox" name="colors[]" value="green"> Green</label></p>
PHP:
$form = new Form\Validator([
'colors' => ['each' => ['in' => array('red','blue','green')]]
]);
$form->validate($_POST);
The above code will check that each colors in either "red", "blue" or "green".
The rule each
is also special in that it will not appear "as it" in the errors. Instead, the index of the offending value will be returned. For example:
// Input values are:
// ['colors' => ['red', 'blue', 'yellow']]
$form->getErrors();
// [
// 'colors' => [
// 2 => [
// 'in' => array('red','blue','green')
// ]
// ]
// ]
It's possible to pass another instance of Form\Validator
as a rule - in this case it is called a "sub-validator".
This is used when a element to be validated contains more elements to be validated, such as when passing a object or a assoc array. For example, let's say your input is (in JSON):
{
"id": 1
"address": {
"street": "Some street",
"postcode": 42,
"city": "Some city"
}
}
You can validate it with:
$form = new Form\Validator([
'id' => ['required'],
'address' => new Form\Validator(array(
'street' => ['required']
'postcode' => ['required']
'city' => ['required']
))
));
It is also possible to combine each
and a sub-validator, for example if you want validate an array of assoc arrays.
Any special validation need can be fulfilled with a custom rule. You can pick any name for your custom rule and pass a callable, for example a closure.
The callback takes 2 parameters: the value, and the form object itself (in case you need to access it).
The callback must return true
on success or false
on failure.
Example:
$identical_password_validator = function($confirmation, $form) {
return $form->password == $confirmation;
};
$form = new Form\Validator([
'password' => ['required', 'min_length' => 6],
'password_confirm' => ['required', 'identical' => $identical_password_validator]
]);
$form->validate(array('password' => 'abcdef', 'password_confirm' => 'abcdef'); // true
$form->validate(array('password' => 'abcdef', 'password_confirm' => 'x')); // false with 'identical' validation error
Important Fields are processed in order, so a callback can only access values of the fields already processed. For example, the following code will NOT work:
$form = new Form\Validator([
// the callback will be called before password has been validated, so $form->password will not be available!
'password_confirm' => ['required', 'identical' => $identical_password_validator],
'password' => ['required', 'min_length' => 6]
]);
The name of your custom rule will used in the errors array if the validation fails. For example in the previous example the value returned by getErrors()
would look like:
['password_confirm' => ['identical' => true]]