Yii form model validation- either one is required

后端 未结 8 985
时光取名叫无心
时光取名叫无心 2020-12-11 15:27

I have two fields on the form ( forgotpassword form ) username and email Id . User should enter one of them . I mean to retrieve the password user can enter user name or th

8条回答
  •  天涯浪人
    2020-12-11 16:28

    Something like this is a bit more generic and can be reused.

    public function rules() {
        return array(
            array('username','either','other'=>'email'),
        );
    }
    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;
    }
    

提交回复
热议问题