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;
}
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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments