2016-11-28 36 views
0

將驗證規則用於CI3中的配置文件時,我無法確定將回調放在哪裏。這裏是我的form_validation.php:將CI3 /驗證規則添加到配置文件並使用回調

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

$config = array(
    'blog_post' => array(

     array(
     'field' => 'entry_name', 
     'label' => 'entry_name', 
     'rules' => 'min_length[8]|trim|required|max_length[255]' 
     ), 

     array(
     'field' => 'entry_body', 
     'label' => 'entry_body', 
     'rules' => 'trim|required|min_length[12]|callback_html_length_without_html' 
     ), 
    ), 
); 

function html_length_without_html(){ 
    if (2 < 1) 
    { 
     $this->form_validation->set_message('html_length_without_html', 'The field can not be the word'); 
     return FALSE; 
    } else { 
     return TRUE; 
    } 
} 

然而,當我運行上面,我得到以下錯誤:

Unable to access an error message corresponding 
to your field name entry_body.(html_length_without_html) 

在哪裏放置回調 「html_length_without_html()」?

+0

也許閱讀用戶指南將會給出答案。 https://www.codeigniter.com/userguide3/libraries/form_validation.html#callbacks-your-own-validation-methods – TimBrownlaw

+0

是的,閱讀過,顯然沒有得到它。 – user3264461

+0

那麼那個函數會放在你正在執行實際驗證的控制器中。使用表單驗證配置來配置驗證規則的相同控制器。 – TimBrownlaw

回答

1

您可以extend或在控制器內創建一個方法。我更喜歡用助手功能「擴展」。假設你正在使用$_POST

應用程序/傭工/ form_validation_helper.php或只是MY_form_helper.php延伸:

<?php 

if (! defined('BASEPATH')) exit('No direct script access allowed'); 

if (!function_exists('html_length_without_html')) { 

function html_length_without_html() { 
    $ci = & get_instance(); 
    $entry_body = $ci->input->post('entry_body'); 
    /*Do some check here to define if is TRUE or FALSE*/ 
    if ($entry_body < 1) { 
     $ci->form_validation->set_message('html_length_without_html', 'The field can not be the word'); 
     return FALSE; 
    } 
    else { 
     return TRUE; 
    } 
} 

} 

沒有錯$ci->form_validation->set_message('html_length_without_html', 'The field can not be the word');,但如果您使用的是郎類,你應該保存以下行application/language/english/form_validation_lang.php獲得全成回調響應:

$lang['html_length_without_html'] = 'The field can not be the word'; 

不要忘了加載使用前助手它代之以:$this->load->helper('form_validation_helper');autoload

+0

更正:它應該是$ this-> load-> helper('form_validation'); _helper.php部分隱含,因爲它是一個幫手。 – TimBrownlaw

+0

刪除了此評論。 – user3264461

+0

我正在使用POST,PUT(GET,DELETE)。當然,POST和PUT是會受到影響的罪魁禍首。這是通過Phil Sturgeon的API服務器。 – user3264461

相關問題