Validation
The Validator is a data validation class that helps minimize the amount of code you need to write.
Validating
Validating POST:
use Inphinit\Experimental\Utility\Validator;
$validator = Validator::post();
$validator->field('name', $name, 'required|min:5|max:15|regex:/^\S+$/');
$validator->field('surname', $surname, 'min:5|max:50');
// strings such as yes, true, and 1 return bool(true)
// strings such as no, false, and 0 return bool(false)
// Other values return null
$validator->field('active', $active, 'required|bool');
if ($validator->valid()) {
echo 'Name: ', htmlentities($name);
if ($surname !== null) {
echo ' ', htmlentities($surname);
}
echo '<br>';
echo $active ? '✔️' : '❌';
} else {
foreach ($validator->failures() as $failure) {
echo '<div class="error"><p>', $failure, '</p></div>';
}
}
Validating GET:
use Inphinit\Experimental\Utility\Validator;
$validator = Validator::get();
$validator->field('query', $query, 'min:5');
$validator->field('type', $type, 'in:electronics,motors,fashion,sports');
$validator->field('sold', $sold, 'bool');
if ($validator->valid()) {
...
}
Validating Arrays and JSONs.
use Inphinit\Experimental\Utility\Validator;
$arr = [
'foo' => '...',
];
$validator = new Validator($arr);
$validator->field('foo', $phone, 'required|regex:/^(?:55)?([1-9]{2})(9?[2-9]\d{3}\d{4})$/');
if ($validator->valid()) {
...
}
use Inphinit\Http\Request;
use Inphinit\Experimental\Utility\Validator;
$app->action('POST', '/receive', function () {
$body = file_get_contents('php://input');
if (strlen($body) < 1) {
Request::status(400);
return 'Invalid request';
}
$decoded = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE || is_array($body) === false) {
Request::status(400);
return 'Invalid body';
}
$validator = new Validator($decoded);
...
});
Validation Rules
Before validation, the values are converted to a string:
| Rule | Combinations | Description |
|---|---|---|
bool |
Can be combined with in and required |
String values such as yes, true, 1, no, false, and 0 |
decimal |
Can be combined with in, regex, min, max, and required |
Validates that the field contains a decimal number string. The separator can be set using: decimal:., decimal:,, decimal:'
|
digit |
Can be combined with in, regex, min, max, and required |
Validates that the field contains a string written as an integer |
email |
Can be combined with in, regex, min, max, and required |
Validates an email address using FILTER_VALIDATE_EMAIL |
in: |
Can be combined with in, regex, min, max, and required
|
Checks if the field's value is one of the values in the provided list; example: in:foo,bar,baz |
ip |
Can be combined with in, regex, min, max, and required |
Validates an IP address using FILTER_VALIDATE_IP |
max:<n> |
If used with decimal or digit, it compares directly against the field's value:
field <= max; for other rules, it compares against the number of characters:
strlen(field) <= max
|
|
min:<n> |
If used with decimal or digit, it compares directly against the field's value: field >= min; for other rules, it will compare against the number of characters: strlen(field) >= min
|
|
regex:<n> |
Validates the field using a custom regular expression, example: regex:/^[A-Z]+$/
|
|
required |
Can be combined with all rules | Makes the field mandatory |
url |
Can be combined with in, regex, min, max, and required
|
Validates a URL using FILTER_VALIDATE_URL and checks if the scheme is https or http
|
Customizing the messages
By default, error messages are in English, but it is possible to modify them and configure them to work with any language system you choose to use, such as Gettext.
The first %s contains the field name or path. As for messages that contain more than one %s, the explanations follow:
| Message | Default | Note |
|---|---|---|
bool |
%s can have values such as Yes, True, 1, No, False, and 0 |
|
decimal |
%s expects a decimal format |
|
digit |
%s expects a digit format |
|
email |
%s expects a valid email |
|
in |
%s has an unexpected value |
|
ip |
%s expects a valid IP |
|
max |
%s expects a maximum %s of %s |
The second %s represents the type, and the third represents the maximum value. |
min |
%s expects a minimum %s of %s |
The second %s represents the type, and the third represents the minimum value. |
regex |
%s does not match the expected format |
|
required |
%s is required |
|
type |
%s contains an unexpected type |
|
unicode_error |
%s contains invalid Unicode characters |
This is not part of the validation process, however, in cases where a field contains problematic characters, this is handled as one of the failures, rather than as an exception, to prevent the system from breaking |
url |
%s expects a valid url |
Example of customization using gettext:
$validator = Validator::post();
$validator->setMessage('bool', _('boolId'));
$validator->setMessage('decimal', _('decimalId'));
$validator->setMessage('digit', _('digitId'));
$validator->setMessage('email', _('emailId'));
$validator->setMessage('in', _('inId'));
$validator->setMessage('ip', _('ipId'));
$validator->setMessage('max', _('maxId'));
$validator->setMessage('min', _('minId'));
$validator->setMessage('regex', _('regexId'));
$validator->setMessage('required', _('requiredId'));
$validator->setMessage('type', _('typeId'));
$validator->setMessage('unicode_error', _('unicode_errorId'));
$validator->setMessage('url', _('urlId'));
The .po file should contain something like:
msgid "boolId"
msgstr "O valor deve ser yes ou no."
msgid "decimalId"
msgstr "O valor deve ser um número decimal."