vjik/yii2-rules-validator

Yii2 validator with nested rules

2.1.0 2020-07-15 10:30 UTC

This package is auto-updated.

Last update: 2024-04-15 18:32:43 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],
        ];
    }
}