vjik / yii2-rules-validator
带有嵌套规则的 Yii2 验证器
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-09-15 19:15:44 UTC
README
安装
安装此扩展的首选方法是使用 composer
composer require vjik/yii2-rules-validator
示例
在模型中使用
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".'); } } }
规则继承
规则类
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".'); } } }
模型
class MyModel extends Model { public $country; public function rules() { return [ ['country', MyRulesValidator::class], ]; } }