Run validation if new record


What is the best way to run a validation if the record is a new record. I use to use scenarios in Yii 1 for this because we had the "insert" scenario by default. But Yii 2 does not seem to have this and I have to define the scenarios manually.

I tried doing this …

["upload", "required", "when" => function($model) { return $model->isNewRecord; }],

But it does not work as the isNewRecord property does not appear to be set at the point in time the validation code is run.

Is there a way to do this without using scenarios?

Just try normal scenario concept

[['name', 'email', 'password'], 'required', 'on' => 'register'],

In controller

$model = new User(['scenario' => 'register']);


Ok will use scenarios.


Works good, I thought Yii 2 forced me to define a scenarios method.

I guess I only need to define that if I do not want certain attributes to belong to a scenario though. Which in this case I do not so it was easy.