arrow_back
Back

Yii2 model validation: rules, custom validators, and behaviors

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

Validation rules are declared in the rules() method of a model:

public function rules()
{
    return [
        // ...
        [['url'], 'validateUrl'],
    ];
}

Inline validators

A rule can point to a method of the model itself:

public function validateUrl($attribute, $params)
{
    if (!in_array($this->$attribute, ['USA', 'Indonesia'])) {
        $this->addError($attribute, 'The country must be either "USA" or "Indonesia".');
    }
}

The method must be accessible to the validator, so declare it public.

Built-in validators

yii\validators\RangeValidator — checks that the value is one of the listed options:

[
    // checks if "level" is 1, 2 or 3
    ['level', 'in', 'range' => [1, 2, 3]],
]

Behaviors for models

A behavior extends a class with reusable functionality.

yii\behaviors\TimestampBehavior

Sets timestamps when a record is created or updated:

public function behaviors()
{
    return [
        TimestampBehavior::class,
    ];
}

By default TimestampBehavior fills the created_at and updated_at attributes with the current timestamp when the Active Record object is inserted, and fills updated_at when it is updated. The value comes from time().

Because these values are set automatically, they are not user input and should not be validated — created_at and updated_at should not appear in the model’s rules().

Custom attribute names:

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::class,
            'createdAtAttribute' => 'create_time',
            'updatedAtAttribute' => 'update_time',
        ],
    ];
}

Only one field:

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::class,
            'updatedAtAttribute' => false,
        ],
    ];
}

yii\behaviors\BlameableBehavior

Automatically records who created or updated a record.

yii\behaviors\SluggableBehavior

Automatically generates a slug from one of the fields.

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 logging: targets, configuration, and VarDumper

arrow_forward