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

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »


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;
            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() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.

        return array(
            array('firma', 'thisOrThatRequired', 'check' => 'vorname,nachname,anrede','on'=>'insert,rework'),
1 3
Viewed: 10 523 times
Version: Unknown (update)
Category: How-tos
Written by: Kabinenkoffer
Last updated by: Kabinenkoffer
Created on: May 8, 2014
Last updated: 10 years ago
Update Article


View all history

Related Articles