2011-01-27 74 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