hikmatkhan
hikmatkhan

Reputation: 23

How to validate Yii2 dynamic model

I was working on Yii2 and would like to dynamically validate the field, like validate if another field is not selected.

I found below code on Yii2 documentation:

['state', 'required', 'when' => function($model) {
    return $model->country == 'USA';
}]

But the thing is that I am using Yii2 dynamic model. How could I achieve the same thing shown above in dynamic model.

Upvotes: 2

Views: 1120

Answers (1)

Anton Rybalko
Anton Rybalko

Reputation: 1314

As usual model:

$model = new \yii\base\DynamicModel([
    'name', 'country', 'state'
]);

$model->addRule(
    'state', 'required', ['when' => function($model) {
        return $model->country == 'USA';
    }
]);

Upvotes: 3

Related Questions