gpt4 book ai didi

validation - CakePHP - 使用相同规则验证多个字段

转载 作者:行者123 更新时间:2023-12-01 12:42:55 25 4
gpt4 key购买 nike

假设我有十几个单选按钮字段,我想根据两个通用规则对其进行验证。

   '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;
}

关于validation - CakePHP - 使用相同规则验证多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22688995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com