Special Validation Rule - Fill out a Field or another group of Fields

How-To use a special validation rule

If you have a form, you sometimes need special validation Rules not included in Yii. Here i share a special rule with you, i just wrote. Maybe you have the case, when a user needs to Fill ou Field A oder the Fields B, C and D.

public function thisOrThatRequired($attribute, $params) {
        if ($params['check']) {
            $check = explode(',', $params['check']);
            $txt = "";
            foreach ($check as $item) $txt.=$this->getAttributeLabel($item).", ";
            $txt = substr($txt, 0,-2);
            
            if ($this->$attribute) $input1=true; 
            else $input1=false;
            
            $input2_komplett=true;
            $input2_teilweise=false;
            foreach ($check as $item) {
                if (!$this->$item) $input2_komplett=false;
                if ($this->$item) $input2_teilweise=true;
            }
            
            // Main field empty but at least 1 empty subfield
            if ((!$input1 && !$input2_komplett && $input2_teilweise)) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . " or together with: " . $txt);
                foreach ($check as $item) {
                    if (!$this->$item) $this->addError($item, $this->getAttributeLabel($item)." together or leave blank (".$txt.")");
                }
            }
            
            // all empty
            elseif (!$input1 && !$input2_komplett) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . " oder folgende Felder zusammen angegeben: " . $txt);
            } 
            
            // Mainfiled but one Subfield empty
            elseif (!$input2_komplett && $input2_teilweise) {
                foreach ($check as $item) {
                    $this->addError($item, $this->getAttributeLabel($item) . " leer lassen oder mit folgenden Feldern ausfüllen: " . $txt);
                }
            }
            
            
        }
    }
public function rules() {
        return array(
            ....
            array('firma', 'thisOrThatRequired', 'check' => 'vorname,nachname,anrede','on'=>'insert,rework'),
            ...
    }
1 3
3 followers
Viewed: 10 800 times
Version: 1.1
Category: How-tos
Written by: Kabinenkoffer
Last updated by: Kabinenkoffer
Created on: May 8, 2014
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles