vjik / yii2-rules-validator
Yii2 validator with nested rules
2.1.0
2020-07-15 10:30 UTC
Requires
- php: >=7.1.0
- yiisoft/yii2: ^2.0.34
Requires (Dev)
- phpunit/phpunit: ^7.5
- yiisoft/yii2-coding-standards: 2.*
This package is auto-updated.
Last update: 2024-12-15 19:47:26 UTC
README
Installation
The preferred way to install this extension is through composer:
composer require vjik/yii2-rules-validator
Examples
Use in model
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:
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:
class MyModel extends Model { public $country; public function rules() { return [ ['country', MyRulesValidator::class], ]; } }