Search code examples
phpvalidationyiiactive-form

Yii2: Either one field is required Validation


I have to implement the validation as mentioned in the title that either one of the two fields (email, phone) is required. I am doing this in my model:

[['email'],'either', ['other' => ['phone']]],

And this is the method:

 public function either($attribute_name, $params) {
        $field1 = $this->getAttributeLabel($attribute_name);
        $field2 = $this->getAttributeLabel($params['other']);
        if (empty($this->$attribute_name) && empty($this->$params['other'])) {
            $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
            return false;
        }
        return true;
    }

When I access my index page, it gives me this error:

Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\validators\InlineValidator::0'

Any help?


Solution

  • The rule should be:

    ['email', 'either', 'params' => ['other' => 'phone']],
    

    And method:

    public function either($attribute_name, $params)
    {
        $field1 = $this->getAttributeLabel($attribute_name);
        $field2 = $this->getAttributeLabel($params['other']);
        if (empty($this->$attribute_name) && empty($this->{$params['other']})) {
            $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
        }
    }