Search code examples
validationcakephpmodel-validation

Model validation in CakePHP check that atleast one or the other is set


Is there a way to validate data (using CakePHP's model validation) to make sure that at least "a" or "b" has data (does not have to have data in both).


Solution

  • In your model, do something like this. The function will be called when you perform a save operation.

    EDITED

    public $validate = array(
        'a' => array(
            'customCheck' => array(
                'rule' => 'abCheck',
                'message' => 'You must enter data in a or b.'
            )
        ),
        'b' => array(
            'customCheck' => array(
                'rule' => 'abCheck',
                'message' => 'You must enter data in a or b.'
            )
        )
    );
    
    //Function must be public for Validator to work
    //Checks to see if either a or b properties are set and not empty
    public function abCheck(){
        if((isset($this->data['Model']['a']) && !empty($this->data['Model']['a'])) || (isset($this->data['Model']['b']) && !empty($this->data['Model']['b']))){
             return true;
        }
        return false;
    }