validation之CakePHP之使用相同规则验证多个字段
mfryf
阅读:142
2025-02-15 21:57:57
评论:0
假设我有十几个单选按钮字段,我想根据两个通用规则对其进行验证。
'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;
}
请您参考如下方法:
将它们添加到 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;
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。