Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vjik/yii2-rules-validator
Yii2 validator with nested rules
https://github.com/vjik/yii2-rules-validator
Last synced: about 5 hours ago
JSON representation
Yii2 validator with nested rules
- Host: GitHub
- URL: https://github.com/vjik/yii2-rules-validator
- Owner: vjik
- License: mit
- Created: 2020-07-08T09:38:29.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2020-07-15T10:31:37.000Z (over 4 years ago)
- Last Synced: 2024-10-26T13:44:21.979Z (24 days ago)
- Language: PHP
- Homepage:
- Size: 13.7 KB
- Stars: 2
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Yii2 validator with nested rules
## Installation
The preferred way to install this extension is through [composer](https://getcomposer.org/download/):
```
composer require vjik/yii2-rules-validator
```## Examples
### Use in model
```php
class MyModel extends Model
{public $country;
public function rules()
{
return [
[
'country',
RulesValidator::class,
'rules' => [
['trim'],
['string', 'max' => 191],
['validateCountry'],
],
],
];
}public function validateCountry($attribute, $params, $validator)
{
if (!in_array($this->$attribute, ['Russia', 'USA'])) {
$this->addError($attribute, 'The country must be either "Russia" or "USA".');
}
}
}
```### Rule Inheritance
Rule class:
```php
class MyRulesValidator extends RulesValidator
{protected function rules(): array
{
return [
['trim'],
['string', 'max' => 191],
['validateCountry'],
];
}public function validateCountry($model, $attribute, $params, $validator)
{
if (!in_array($model->$attribute, ['Russia', 'USA'])) {
$model->addError($attribute, 'The country must be either "Russia" or "USA".');
}
}
}
```Model:
```php
class MyModel extends Model
{public $country;
public function rules()
{
return [
['country', MyRulesValidator::class],
];
}
}
```