如何在codeigniter中为多个文本字段使用相同的回调函数

时间:2015-08-03 05:52:16

标签: php codeigniter validation

我想检查值是否不是整数和浮点数,我已经编写了表单验证,如下所示,

$this->form_validation->set_rules('charge_hour', 'Per hour', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_day', 'Per day', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_weekly', 'Per week', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_monthly', 'Per month', 'xss_clean|callback_money_type');

所有文本字段的常用回调函数为money_type()

    public function money_type($charge)
        {
            if (is_float($charge) == false && is_int($charge) == false && $charge >= 0)
            {
                $this->form_validation->set_message('{WHAT TO ENTER HERE}', 'Enter valid charges for space.');
                return FALSE;
            }
        else
        {
            return TRUE;
        }
    }

如何在验证过程中找到{输入什么内容}?字段名称是运行时的charge_hour,charge_day,charge_weekly,charge_monthly?这样表单验证将为每个字段显示不同的错误消息。

感谢。

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

您可以在回调参数

中传递您的文件名
$this->form_validation->set_rules('charge_hour', 'Per hour', 'xss_clean|callback_money_type[charge_hour]');
$this->form_validation->set_rules('charge_day', 'Per day', 'xss_clean|callback_money_type[charge_day]');
$this->form_validation->set_rules('charge_weekly', 'Per week', 'xss_clean|callback_money_type[charge_weekly]');
$this->form_validation->set_rules('charge_monthly', 'Per month', 'xss_clean|callback_money_type[charge_monthly]');

你回调函数

public function money_type($charge,$fild_name)
        {
            if (is_float($charge) == false && is_int($charge) == false && 

    $charge >= 0)
                {
                    $this->form_validation->set_message("{$fild_name}", 'Enter valid charges for space.');
                    return FALSE;
                }
            else
            {
                return TRUE;
            }
        }

答案 2 :(得分:0)

我得到了答案,我的错误在这里。

{WHAT TO ENTER HERE}应与回调函数名称function money_type相同,然后它将适用于所有字段回调

$ this-> form_validation-> set_message(' {输入什么内容}','输入有效的空间费用。');

应该是

$ this-> form_validation-> set_message(' money_type','输入有效的空间费用。');