Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - Validating multiple fields with same rule

Let's say I have a dozen radio button fields which I want to validate against two common rules.

   'valid'=> array(
        'rule' => array('inList', array('yes','no')),
        'message' => 'Illegal Choice Detected'

   ),
   'required'=> array(
       'rule' => array('notEmpty'),
       'message' => 'Field is required.'
   ),

How can I do this without having to assign each validation rule to each field ?

[EDIT]

For those how prefer some spoon feeding as I myself like sometimes, Here is how I did it based on Burzum's answer!

   public function beforeValidate($options = []) {
        $fields = ['field_1','field_2','field_3','etc'];
        foreach ($fields as $field) {            
            $this->validate[$field]['required'] = array(
                    'rule' => array('notEmpty'),
                    'message' => 'Field is required.'
            );
            $this->validate[$field]['legal'] = array(
                    'rule' => array('inList', array('yes', 'no')),
                    'message' => 'An illegal choice has been detected, please contact the website administrator.'
            );
        }
        return true;
    }
like image 564
LogixMaster Avatar asked Feb 03 '26 07:02

LogixMaster


1 Answers

Add them in a foreach loop in beforeValidate()

public function beforeValidate($options = []) {
    $fields = ['field1', '...'];
    foreach ($fields as $field) {
        // Add your rule(s) here to the field
        $this->validate[$field]['myRule'] = ['...'];
    }
    return true;
}
like image 154
floriank Avatar answered Feb 05 '26 07:02

floriank