假设我有十几个单选按钮字段,我想根据两个常见规则进行验证。
'valid'=> array(
'rule' => array('inList', array('yes','no')),
'message' => 'Illegal Choice Detected'
),
'required'=> array(
'rule' => array('notEmpty'),
'message' => 'Field is required.'
),
如何在不必将每个验证规则分配给每个字段的情况下执行此操作?
[编辑]
对于那些喜欢有时像我自己喜欢的勺子喂食的人来说,这就是我根据Burzum的答案做到的!
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;
}
答案 0 :(得分:4)
在beforeValidate()
中的foreach循环中添加它们public function beforeValidate($options = []) {
$fields = ['field1', '...'];
foreach ($fields as $field) {
// Add your rule(s) here to the field
$this->validate[$field]['myRule'] = ['...'];
}
return true;
}