How to validate Yii2 dynamic model

Viewed 608

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.

1 Answers

As usual model:

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

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