Yii form model validation- either one is required

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

    Yii 1

    It can be optimized of course but may help someone

    class OneOfThemRequiredValidator extends \CValidator
    {
        public function validateAttribute($object, $attribute)
        {
            $all_empty = true;
            foreach($this->attributes as $_attribute) {
                if (!$this->isEmpty($object->{$_attribute})) {
                    $all_empty = false;
                    break;
                }
            }
    
            if ($all_empty) {
                $message = "Either of the following attributes are required: ";
                $attributes_labels = array_map(function($a) use ($object) {
                        return $object->getAttributeLabel($a);
                    }, $this->attributes);
                $this->addError($object, $_attribute, $message . implode(',', 
                $attributes_labels));
            }
        }
    }
    

提交回复
热议问题