【问题标题】:Codeigniter form validation callback function not workingCodeigniter 表单验证回调函数不起作用
【发布时间】:2010-11-24 14:22:17
【问题描述】:

我编写了一个不起作用的简单回调函数。我的其他回调(在同一个库文件中)工作正常,所以我猜这个问题与我的代码有关。

在回调函数中传递的参数采用 PHP 块的形式,该块被 eval()'ed 以形成函数本身中“if()”语句的一部分。

这是控制器中的内容:

$this->form_validation->set_rules('rating', 'Rating','required');
$condition = $this->input->post('rating')  . " != 'Excellent'";
$this->form_validation->set_rules('details', 'Details', 'required_conditional[' . htmlentities($condition) .']');

这是回调函数本身:

function required_conditional($str, $condition)
{
    if (eval(html_entity_decode($condition))) {
        if ($str == '') {
            $this->set_message('required_conditional', 'The %s field is required');
            return FALSE;
        }
        else {
            return TRUE;
        }
    }
}

任何想法为什么它对任何人都不起作用?

谢谢,马特

【问题讨论】:

  • 介意发布一些 $condition 的例子吗?
  • 见第一个代码sn -p的第二行。

标签: php codeigniter function validation callback


【解决方案1】:

这是因为eval 计算的是语句,而不是表达式。这会给你一个解析错误:

$test = "1 > 0";
if (eval($test)) { echo "echo!"; }

这将按您的预期工作:

$test = "return 1 > 0;";
if (eval($test)) { echo "echo!"; }

【讨论】:

  • 好的,所以在我上面的例子中,我应该将 $condition 更改为:return $this->input->post('rating') 。 " != '优秀'"; ??我实际上在那里创建了一个简化的示例。我真正需要做的是: $condition = "('" . $this->input->post('exterior_condition_rating') . "' != '-1') && ('" . $this->input ->post('exterior_condition_rating') . "' != '5 - 优秀')";那么我该如何让它发挥作用呢?
  • 抱歉,没有意识到换行符会被删除。希望它仍然可读!
  • $condition = "return ('" . $this->input->post('exterior_condition_rating') . "' != '-1') && ('" . $this->input->post('exterior_condition_rating') . "' != '5 - Excellent');"
【解决方案2】:

你不应该使用“callback_<function name>”吗?

【讨论】:

  • 我已经扩展了验证类并将函数包含在其中,因此无需使用 callback_ 前缀。
【解决方案3】:

是的,调用表单验证回调的正确语法是使用“callback_”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 2011-12-09
    相关资源
    最近更新 更多