Validation
The Validator is a data validation class that helps minimize the amount of code you will need to write.
Validating
Validating POST:
use Inphinit\Experimental\Validation\Validator;
$validator = Validator::post();
$validator->field('name', $name, 'required|min:5|max:15|regex:/^\S+$/');
$validator->field('surname', $surname, 'min:5|max:50');
// strings with yes, true e 1 returns bool(true)
// strings with no, false e 0 returns bool(false)
// Outros valores retornam null
$validator->field('active', $active, 'required|bool');
if ($validator->valid()) {
echo 'Nome: ', 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\Validation\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\Validation\Validator;
$arr = [
'foo' => [
'bar' => [
'baz' => '...',
]
]
];
$validator = new Validator($arr);
$validator->field('foo.bar.baz', $phone, 'required|regex:/^(?:55)?([1-9]{2})(9?[2-9]\d{3}\d{4})$/');
if ($validator->valid()) {
...
}
use Inphinit\Http\Request;
use Inphinit\Experimental\Validation\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 strings:
| Rule | Combinations | Description |
|---|---|---|
boolean |
It can be combined within |
String values such as yes, true, 1, no, false, and 0 |
decimal |
It can be combined with in, regex, min, max |
Validates whether the field received a decimal number string. The separator can be adjusted using:
decimal:., decimal:, , decimal:'
|
integer |
It can be combined with in, regex, min, max |
Validates whether the field received a string written as an integer. |
email |
It can be combined with in, regex, min, max |
Validate URL usingFILTER_VALIDATE_EMAIL
|
equal:<field name> |
Compares the field with another field. This can be useful for comparing a password field with a confirmation field. | |
in: |
It can be combined with in, regex, min, maxandrequired
|
Checks if the field value is one of the values in the list, for example:in:foo,bar,baz |
max:<n> |
If used with decimal and integer, it will directly compare the value of the field
campo <= max; for the other rules, it will compare the number of characters.
strlen(campo) <= max
|
|
min:<n> |
If used with decimal and integer, it will directly compare the value of the field
campo >= min; for the other rules, it will compare the number of characters.
strlen(campo) >= min
|
|
regex:<n> |
Validates the field with a custom regular expression, for example:regex:/^[A-Z]+$/
|
|
required |
It can be combined with all rules. | Make the field mandatory. |
url |
It can be combined with in, regex, min, maxandrequired
|
Validates URL using FILTER_VALIDATE_URLand checking if the scheme is httpsorhttp
|
Customizing messages
By default, error messages are in English, but it is possible to modify and configure them with any language system you use, such as Gettext...
The first %scontains the name or path of the field. As for messages containing more than one %s, the following explanations apply:
| Message | Standard | Notice |
|---|---|---|
boolean |
Must be a boolean value (on, yes, true, 1, off, no, false or 0) |
|
decimal |
Must be a valid decimal number |
|
email |
Must be a valid email address |
|
equals |
Must match the \'%s\' field |
|
in |
Must be one of the allowed values |
|
integer |
Must be a valid integer |
|
invalid |
Invalid value |
|
max |
Enter no more than %s characters |
|
min |
Enter at least %s characters |
|
max_numeral |
Enter a number no greater than %s |
|
min_numeral |
Enter a number greater than or equal to %s |
|
regex |
Invalid format |
|
required |
This field is required |
|
type |
Invalid type: expected a string, number or boolean |
|
unicode_error |
Contains invalid Unicode (UTF-8) characters |
Não faz parte da validação, mas em casos que um campo tem caracteres com problema, isso é tratado com uma das falhas, ao invés de uma exceção, para evitar quebras. |
regex_issue |
Failed to resolve pattern |
It's not part of the validation, but in cases where a field has problematic characters, this is handled as one of the failures, rather than an exception, to avoid code breakage. |
url |
Must be a valid HTTP or HTTPS url |
Example of customization with gettext:
$validator = Validator::post();
$validator->setMessage('bool', _('boolId'));
$validator->setMessage('decimal', _('decimalId'));
$validator->setMessage('int', _('intId'));
$validator->setMessage('email', _('emailId'));
$validator->setMessage('integer', _('inId'));
$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 file .poshould contain something like:
msgid "boolId"
msgstr "O valor deve ser yes ou no."
msgid "decimalId"
msgstr "O valor deve ser um número decimal."
Extended rules
In addition to the standard rules, Inphinit provides a number of additional rules, extending support:
| Rule | Combinations | Description |
|---|---|---|
cnpj |
Validates CNPJ (Brazil) in numeric dd.ddd.ddd/dddd-ddand alpha-numeric format AA.ADD.DAD/DDDD-DD(IN RFB 2.229/2024).
|
|
cpf |
Validates CPF (Brazil). | |
cpfcnpj |
It verifies whether it's a CPF (Brazilian individual taxpayer registration number) or CNPJ (Brazilian company taxpayer registration number), allowing both. | |
ip |
Validate IP | |
password |
in, regex, min, max |
Validate passwords |
Para customizar as mensagens de uma regra extendida use o método Validator::getRuleInstange():
$validator->getRuleInstance('ip')->setMessage('default', 'Enter a valid IP');
$validator->getRuleInstance('password')
->setMessage('lower', 'Enter at least one lowercase character.')
->setMessage('special', 'Enter at least one special character.')
->setMessage('upper', 'Enter at least one uppercase character.');
Creating your own rules
It is possible to create your own rules by defining classes that extend Inphinit\Experimental\Validation\Rule:
<?php
namespace Foo;
use Inphinit\Experimental\Validation\Rule;
class BarRule extends Rule
{
// Set allowed combinations
protected $alloweds = array(...);
// Set messages for failed validations
protected $messages = array(...);
public function exec($path, &$value, array $params, array $rules)
{
$this->isAllowed($rules);
if ($value === 'AAA') {
$this->failure = $this->messages['default'];
}
return $this->passed();
}
}
Uso:
use Inphinit\Http\Response;
use Inphinit\Http\Status;
$validator->setRule('sample1', Foo\BarRule::class);
$validator->setRule('sample2', Foo\BazRule::class);
$validator->field('fieldA', $var1, 'sample1');
$validator->field('fieldB', $var2, 'sample1');
if ($validador->valid()) {
echo json_encode(['response' => true]);
} else {
Response::status(Status::HTTP_BAD_REQUEST);
echo json_encode($validators->failures());
}