k0pernikus
k0pernikus

Reputation: 66510

How to validate for either one or another field in a model using yii1.1?

In a [email protected] project, I have a model having a field event_id with the rules:

public function rules(): array
{
    return [
        ['event_id', 'required'],
        ['event_id', 'numerical', 'integerOnly' => true],
    ];
}

Now I want to extend the table so that there is also a video_id.

I am unsure though how I can check for either the event_id or the video_id. Is this possible through the rules method or do I need to add some custom validation?

I don't want to make both fields optional because one of them but not both should be set.

Upvotes: 0

Views: 733

Answers (1)

Alberto
Alberto

Reputation: 12929

You can use when

['event_id', 'required', 'when' => function($model) {
    return $model->video_id === null;
}], 
['video_id', 'required', 'when' => function($model) {
    return $model->event_id === null;
}]

Looks like it exists only from 2.X ... instead in 1.X you can use this extension https://www.yiiframework.com/extension/yii-conditional-validator

Upvotes: 1

Related Questions