vjik/yii2-rules-validator Yii2 validator with nested rules

Yii2 validator with nested rules

  1. Installation
  2. Examples

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],
        ];
    }
}
1 0
1 follower
305 downloads
Yii Version: 2.0
License: MIT
Category: Validation
Developed by: vjik
Created on: Jul 17, 2020
Last updated: (not set)
Packagist Profile
Github Repository

Related Extensions