horat1us/yii2-const-range-validator

Yii2 Range Validator using class constants

1.0.0 2019-03-21 04:18 UTC

This package is auto-updated.

Last update: 2024-10-21 21:02:03 UTC


README

Build Status codecov

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

License

MIT