2016-07-14 32 views
0

我有自定義驗證表單在CI3 - form_validation.php。這樣的事情:在自定義form_validation.php中使用幫助函數 - CodeIgniter 3

$config = [ 
'validation_key'=>[ 
    [ 

     'field' => 'name', 
     'label' => 'Name', 
     'rules' => 'trim|required|min_length[2]|max_length[50]|alpha_numeric' 
    ], 
    [ 
     'field' => 'country', 
     'label' => 'name', 
     'rules' => 'in_list[....]' 
    ], 
] 

而且我有幫助函數返回所有國家的數組。我想要的是在國家字段驗證中添加這個幫助函數來檢查它是否是有效的國家名稱。我怎樣才能做到這一點 ?在CI3文檔中,沒有什麼可以在form_validation.php中添加助手。

+0

贖回 - http://www.codeigniter.com/user_guide/ libraries/form_validation.html#callable-use-anything-as-a-rule – cartalot

回答

0

它只有在您添加自定義回話規則並提供內部功能時纔有可能。就像這樣:

$config = [ 
'validation_key'=>[ 
    [ 

     'field' => 'name', 
     'label' => 'Name', 
     'rules' => 'trim|required|min_length[2]|max_length[50]|alpha_numeric|callback_custom_plugin' 
    ], 
    [ 
     'field' => 'country', 
     'label' => 'name', 
     'rules' => 'in_list[....]' 
    ], 
] 

... 

function custom_plugin($value){ 
    return your_helper_function($value); 
} 
0

您的配置文件::

$config = [ 
    'validation_key'=>[ 
       [ 
       'field' => 'name', 
       'label' => 'Name', 
       'rules' => 'trim|required|min_length[2]|max_length[50]|alpha_numeric' 
       ], 
       [ 
       'field' => 'country', 
       'label' => 'name', 
       'rules' => 'required|callback_check_country' 
       ], 
    ] 

在你的控制器:

function check_country($country) 
    { 
    $countryLists = $this->Your_model->getCountryLists(); 

    //print_r($countryLists); 

    //Something similar 

    if (in_array($country , $countryLists)) { 
     return TRUE; 
    } 
    else 
    { 
     $this->form_validation->set_message('check_country', 'Your Country is not found in list !'); 
     return FALSE; 
    } 
    } 
+0

它返回false並顯示消息「無法訪問對應於您的錯誤消息r字段名稱國家。(check_country)「,即使我只在回調函數中添加」返回true「(在任何情況下驗證都是錯誤的)。回調函數工作正常(我檢查了自定義文件) – gdfgdfg

相關問題