Yii form model validation- either one is required

后端 未结 8 982
时光取名叫无心
时光取名叫无心 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:27

    Yii2

    namespace common\components;
    
    use yii\validators\Validator;
    
    class EitherValidator extends Validator
    {
        /**
         * @inheritdoc
         */
        public function validateAttributes($model, $attributes = null)
        {
            $labels = [];
            $values = [];
            $attributes = $this->attributes;
            foreach($attributes as $attribute) {
                $labels[] = $model->getAttributeLabel($attribute);
                if(!empty($model->$attribute)) {
                    $values[] = $model->$attribute;
                }
            }
    
            if (empty($values)) {
                $labels = '«' . implode('» or «', $labels) . '»';
                foreach($attributes as $attribute) {
                    $this->addError($model, $attribute, "Fill {$labels}.");
                }
                return false;
            }
            return true;
        }
    }
    

    in model:

    public function rules()
    {
        return [
            [['attribute1', 'attribute2', 'attribute3', ...], EitherValidator::className()],
        ];
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题