2011-01-27 76 views
21

张贴有两个字段名为“ID”和“URL”,我有以下代码的形式后:笨传递2个参数回调

$this->load->library('form_validation'); 
$this->form_validation->set_rules('id', 'id', 'trim|xss_clean'); 
$this->form_validation->set_rules('url', 'url|id', 'trim|xss_clean|callback_url_check'); 

一个数据库查询需要两个字段。

功能url_check($海峡,$ ID)被调用,但在这种情况下, 'ID' 的值总是0

如果我只是做:

$this->form_validation->set_rules('url', 'url', 'trim|xss_clean|callback_url_check'); 

并调用url_check($str)一切的工作因为它应该这样做。

问题是如何将两个值传递给url_check($str, $id)

+0

不能,你只是concat`$ str。$ id;`并且为了验证而将它传递给它。 – Ross 2011-01-28 09:08:21

回答

35

你可以用$这个 - >输入 - >后直接:

function check_url() { 
    $url = $this->input->post('url'); 
    $id = $this->input->post('id'); 

    // do some database things you need to do e.g. 
    if ($url_check = $this->user_model->check_url($url, $id) { 
     return TRUE; 
    } 
    $this->form_validation->set_message('Url check is invalid'); 
    return FALSE; 
} 
+1

索普,这是天才。伟大的建议,这将完全奏效。 – 2011-01-28 12:31:32

+0

我没有看到这个线程做到了这一点,现在我正在寻找如何做到这一点,因为这不够通用(至少在我的函数中) – Limon 2014-02-11 15:39:42

2

如果我正确理解form_validation,每个规则(set_rules)都是针对表单的一个字段,并且您的回调只会检查一个字段。在你的情况下,'id'似乎超出了范围。相反,可以将数组传递给set_rules函数并执行回调。我还没有尝试过。 http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray

+0

+1这是正确的,CI的set_rules仅适用于每个规则一个字段。您可以使用助手功能或类似(或如您的模型中所建议的)_,这不是理想的,但在这里就是这种情况。 – Ross 2011-01-28 09:07:17

+0

谢谢!你验证了我的想法。 – pigfox 2011-01-29 17:52:55

8

这似乎也工作。

$id = 1; 

$this->form_validation->set_rules('username', 'Human Username', 'callback_username_check['.$id.']'); 

function username_check($str, $id) { 
    echo $id; 
    if ($str == 'test') { 
     $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); 
     return FALSE; 
    } 
    else { 
    return TRUE; 
    } 
} 
+0

它对我不适用 – 2012-01-18 07:25:01

28

只要做到这一点的描述in the docs(至少对于CI 2.1+)的正确方法:

$this->form_validation->set_rules('uri', 'URI', 'callback_check_uri['.$this->input->post('id').']'); 
// Later: 
function check_uri($field, $id){ 
    // your callback code here 
} 
1

只需使用回调参数作为其他答案建议笔记。如果使用app/config/form_validation.php创建验证规则,则$this->input->post('parameter')语法将不起作用,因为该对象在执行时读取该文件内容的位置在CI加载程序中不可用。您必须在回叫例行程序中进行呼叫,例如:

​​

在这种情况下,传递给该方法的第二个参数将不包含密码,但在调用之后$ var。

我希望这很清楚。 Matt