The package provides data validation capabilities.
- Could be used with any object.
Library could be used in two ways: validating a single value and validating a set of data.
<?php$rules = newRules([
newRequired(),
(newNumber())->min(10),
function ($value): Result {
$result = newResult();
if ($value !== 42) {
$result->addError('Value should be 42!');
}
return$result;
}
]);
$result = $rules->validate(41);
if ($result->isValid() === false) {
foreach ($result->getErrors() as$error) {
// ...
}
}<?phpclass MoneyTransfer implements \Yiisoft\Validator\DataSetInterface
{
private$amount;
publicfunction__construct($amount) {
$this->amount = $amount;
}
publicfunctiongetValue(string$key){
if (!isset($this->$key)) {
thrownew \InvalidArgumentException("There is no \"$key\" in MoneyTransfer.");
}
return$this->$key;
}
}
$moneyTransfer = newMoneyTransfer();
$validator = newValidator([ 'amount' => [
(newNumber())->integer()->max(100),
function ($value): Result {
$result = newResult();
if ($value === 13) {
$result->addError('Value should not be 13!');
}
return$result;
}
],
]);
$results = $validator->validate($moneyTransfer);
foreach ($resultsas$attribute => $result) {
if ($result->isValid() === false) {
foreach ($result->getErrors() as$error) {
// ...
}
}
}In order to create your own validation rule you should extend Rule class:
<?phpnamespaceMyVendor\Rules;
useYiisoft\Validator\Result;
useYiisoft\Validator\Rule;
class Pi extends Rule
{
publicfunctionvalidateValue($value): Result
{
$result = newResult();
if ($value != M_PI) {
$result->addError('Value is not PI!');
}
return$result;
}
}In order to reuse multiple validation rules it is advised to group rules into validation sets:
class UsernameRules
{
publicstaticfunctionget(): array
{
return [
(newHasLength)->min(2)->max(20),
newMatchRegularExpression('~[a-z_\-]~i')
];
}
}Then it could be used like the following:
$validator = newValidator([ 'username' => UsernameRules::get(),
'email' => [newEmail()]
]);
$results = $validator->validate($user);
foreach ($resultsas$attribute => $result) {
if ($result->isValid() === false) {
foreach ($result->getErrors() as$error) {
// ...
}
}
}

