Reference
taphra/validator
Input validator for PHP with string rules such as required|email|max:255. One class, no Composer dependencies; it needs only the mbstring extension.
Requirements
#- PHP 8.2+
ext-mbstring
Installation
#composer require taphra/validatorQuick start
#use Taphra\Validator;
$input = [
'email' => '[email protected]',
'age' => '17',
'role' => 'admin',
'password' => 'hunter2',
'confirm' => 'hunter2',
'slug' => 'hello-world',
];
$v = Validator::make($input, [
'email' => 'required|email',
'age' => 'required|integer|min:18|max:120',
'role' => 'required|in:admin,editor,viewer',
'password' => 'required|min:8',
'confirm' => 'required|confirmed:password',
'slug' => 'regex:/^[a-z0-9-]+$/',
]);
if ($v->fails()) {
print_r($v->errors());
// [
// 'age' => ['The age must be at least 18.'],
// 'password' => ['The password must be at least 8.'],
// ]
}Built-in rules
#| Rule | Passes when | Example |
|---|---|---|
required |
the field is present and not null, '' or [] |
required |
nullable |
always; when the field is null or '' the remaining rules are skipped |
nullable|email |
sometimes |
always; when the field is absent the remaining rules are skipped | sometimes|required |
email |
the value is an email address | email |
url |
the value is a URL with an allowed scheme (see below) | url, url:https |
integer |
the value is an integer or an integer string | integer |
numeric |
the value is a number or a numeric string | numeric |
boolean |
the value is true, false, 0, 1, "0", "1", "true" or "false" |
boolean |
alpha |
the value has ASCII letters only | alpha |
alpha_num |
the value has ASCII letters and digits only | alpha_num |
date |
strtotime() can parse the value |
date |
json |
the value is valid JSON | json |
min |
the size is at least the parameter (see below) | min:8 |
max |
the size is at most the parameter (see below) | max:255 |
min_digits |
the value has at least N digit characters | min_digits:6 |
max_digits |
the value has at most N digit characters | max_digits:10 |
in |
the value is one of the listed values | in:admin,editor,viewer |
not_in |
the value is none of the listed values | not_in:banned,suspended |
confirmed |
the value equals another field (default: <field>_confirmation) |
confirmed:password |
regex |
the value matches the pattern | regex:/^[a-z]+$/ |
starts_with |
the value starts with the parameter | starts_with:https |
ends_with |
the value ends with the parameter | ends_with:.com |
phone |
the value has between 7 and 15 digits (or the given range) | phone, phone:10,10 |
domain |
the value is a domain name | domain |
unique |
no row in the given table has the value (see below) | unique:main,users,email |
Rules other than required, nullable and sometimes are skipped when the field is null or ''.
How min and max measure
#- A number (an
intorfloatvalue) is compared by value. - A numeric string is compared by value only when the field also has the
integerornumericrule:integer|min:18rejects"17". - Any other string is compared by its length in characters:
min:8rejects"99". - An array is compared by its number of elements.
Arrays
#An array value fails every rule that expects a single value (email, url, in, regex, integer, and so on). required, min, max, confirmed and custom rules receive the array as it is.
URLs
#url accepts http, https and ftp URLs. Anything else fails, including javascript:, data:, vbscript: and file:. List the schemes you want to allow to change that:
'website' => 'url:https', // https only
'link' => 'url:http,https,mailto', // also mailto:Unknown rules
#A rule name that is neither built in nor registered with Validator::extend() throws an InvalidArgumentException naming the rule and the field, even when the field is empty. A typo such as emial therefore fails loudly instead of letting every value through.
Rules in a pipe string are split on |. A regular expression that contains | must be given in array form:
'code' => ['required', 'regex:/^(abc|def)$/'],Result API
#$v = Validator::make($data, $rules)->validate();
$v->passes(); // true when every rule passed
$v->fails(); // true when any rule failed
$v->errors(); // array<string, string[]>: error messages per field
$v->firstError('email'); // first error for a field, or nullvalidate() runs once; calling it again, or calling passes(), fails() or errors(), reuses the result.
Messages name a field by its input name. attributes() gives fields readable names for every message, built-in or custom (:field); errors() stays keyed by the input name:
$v = Validator::make(['rate_limit_per_minute' => '0'], ['rate_limit_per_minute' => 'integer|min:1'])
->attributes(['rate_limit_per_minute' => 'rate limit']);
$v->errors(); // ['rate_limit_per_minute' => ['The rate limit must be at least 1.']]Custom rules
#Validator::extend(
'even',
function (string $field, mixed $value, array $params, array $data): bool {
return is_numeric($value) && ((int) $value % 2 === 0);
},
':field must be an even number'
);
// Error templates support :field, :param0, :param1, ...
Validator::extend('between', function ($field, $value, $params) {
return $value >= $params[0] && $value <= $params[1];
}, ':field must be between :param0 and :param1');
$v = Validator::make(['n' => '7'], ['n' => 'even|between:1,5']);
$v->errors(); // ['n' => ['n must be an even number', 'n must be between 1 and 5']]A custom rule cannot replace a built-in rule of the same name.
Pipe and array syntax
#Both forms are equivalent:
$rules = ['email' => 'required|email'];
$rules = ['email' => ['required', 'email']];The unique rule
#unique checks that no row in a table already has the value:
'email' => 'unique:connection_name,table,column'
'email' => 'unique:connection_name,table,column,except_column,except_value'The second form ignores the row where except_column equals except_value (for example the record being edited). Table and column names must be plain identifiers (letters, digits and _; the table may be schema.table); anything else throws an InvalidArgumentException. The value is always sent as a bound parameter.
Inside the Taphra framework the database is wired for you. Standalone, register a resolver that returns a connection for the name in the rule:
Validator::setDatabaseResolver(function (string $connection): PDO {
return new PDO('sqlite:/path/to/app.db');
});
$v = Validator::make(['email' => '[email protected]'], ['email' => 'unique:main,users,email']);
$v->firstError('email'); // "The email has already been taken."The resolver may return:
- a
PDO(identifiers are quoted for its driver), - a Taphra
DatabaseConnection(taphra/db), - any object with
query(string $sql, array $bindings): arraythat returns rows with acntcolumn. If it also hasquoteIdentifier(string $name): string, that is used to quote names; otherwise MySQL backticks are used.
Without a resolver the rule throws a LogicException, and database errors are not caught: a uniqueness check that cannot run never reports success.
nullable and sometimes
#// nullable: skip the other rules when the field is empty (optional fields)
$rules = ['bio' => 'nullable|max:500'];
// sometimes: only validate the field when it is present in the input
$rules = ['legacy_field' => 'sometimes|required|integer'];Package layout
#packages/validator/
composer.json
src/
Validator.php # Taphra\Validator, a single class