我想在 codeigniter 表单验证规则中传递多个回调......但只有一个回调有效
我在我的控制器中使用这个语法
$this->form_validation->set_rules(
array(
'field' => 'field_name',
'label' => 'Field Name',
'rules' => 'callback_fieldcallback_1|callback_fieldcallback_2[param]',
'errors' => array(
'fieldcallback_1' => 'Error message for rule 1.',
'fieldcallback_2' => 'Error message for rule 2.',
)
),
);
回调函数是......
function fieldcallback_1 (){
if(condition == TRUE){
return TRUE;
} else {
return FALSE;
}
}
function fieldcallback_2 ($param){
if(condition == TRUE){
return TRUE;
} else {
return FALSE;
}
}
有人请帮我解决这个问题....关于在表单验证规则中传递多个回调的任何其他解决方案也值得赞赏...
所有验证例程必须至少有一个参数,即要验证的字段的值。因此,没有额外参数的回调应该像这样定义。
function fieldcallback_1($str){
return ($str === "someValue");
}
需要两个参数的回调是这样定义的
function fieldcallback_2 ($str, $param){
//are they the same value?
if($str === $param){
return TRUE;
} else {
$this->form_validation->set_message('fieldcallback_2', 'Error message for rule 2.');
//Note: `set_message()` rule name (first argument) should not include the prefix "callback_"
return FALSE;
}
也许像这样?
$this->form_validation->set_rules(
array(
'field' => 'field_name',
'label' => 'Field Name',
'rules' => 'callback_fieldcallback_1[param]'),
);
// Functions for rules
function fieldcallback_1 ($param){
if(condition == TRUE){
return fieldcallback_2($param);
} else {
$this->form_validation->set_message('callback_fieldcallback_1', 'Error message for rule 1.');
return FALSE;
}
}
function fieldcallback_2 ($param){
if(condition == TRUE){
return TRUE;
} else {
$this->form_validation->set_message('callback_fieldcallback_1', 'Error message for rule 2.');
return FALSE;
}
}
使用
serialize()
将多个参数传递给表单验证回调:
public function get_form_input() {
// assemble the parameters into an array, as many as you like
$aryParams = ['item_1' => $value1, 'item_2' => $item2, 'item_3' => $value3];
// serialize the array (creates a string)
$strSerializedArray = serialize($aryParams);
// pass the string to the callback
$this->form_validation->set_rules('form_field_name', 'Your Message', 'callback_validate_form_data['.$strSerializedArray.']');
}
//以及,回调函数:
public function _validate_form_data($form_field, $strSerializedArray) {
// convert the string back to an array
$aryParams = unserialize($strSerializedArray);
// use the array elements, as needed
$item_1 = $aryParams['item_1'];
$item_2 = $aryParams['item_2'];
$item_3 = $aryParams['item_3'];
}