horat1us / yii2-const-range-validator
Yii2 Range Validator using class constants
Installs: 1 402
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=7.2
- yiisoft/yii2: ^2.0.15
Requires (Dev)
- phpunit/phpunit: ^8.0
- squizlabs/php_codesniffer: ^3.4
This package is auto-updated.
Last update: 2024-11-21 21:06:12 UTC
README
This package provides validator that allows use class constants as \yii\validators\RangeValidator::range
.
Main purpose is to prevent errors after adding new constants to classes
(forgot to update validation rule).
Previous implementation was available in horat1us/yii2-base package as ConstRangeValidator.
Installation
Using packagist.org:
composer require horat1us/yii2-const-range-validator:^1.0
Usage
Validator
<?php namespace App; use Horat1us\Yii\ConstRange; use yii\base; class Model extends base\Model { public const TYPE_A = 'A'; public const TYPE_B = 'B'; public $type; public function rules(): array { return [ [['type',], ConstRange\Validator::class,], ]; } } $model = new Model; $model->type = 'C'; $model->validate(); // false $model->type = Model::TYPE_A; $model->validate(); // true
ArrayObject
You can use Yii2 RangeValidator:
<?php namespace App; use Horat1us\Yii\ConstRange; use yii\base; class Model extends base\Model { public const TYPE_A = 'A'; public const TYPE_B = 'B'; public $type; public function rules(): array { return [ [['type',], 'range', 'range' => (new ConstRange\ArrayObject(Model::class, 'TYPE_'))], ]; } } $model = new Model; $model->type = 'C'; $model->validate(); // false $model->type = Model::TYPE_A; $model->validate(); // true