2013-02-01 102 views
4

我試圖使用CodeIgniters表單驗證庫,儘管我的驗證規則似乎工作,只要我調用validation_errors(),我得到一個空字符串。CodeIgniter表單驗證,無法獲取驗證錯誤

這是一段代碼片段。

$base_rules = 'required|trim'; 

$this->_validation_rules = array(
     array(
      'field' => 'name', 
      'label' => 'name', 
      'rules' => $base_rules . '|alpha_numeric|min_length[5]|max_length[30]' 
     ), 
     array(
      'field' => 'price', 
      'label' => 'Price', 
      'rules' => $base_rules . '|decimal' 
     ), 
     array(
      'field' => 'duration', 
      'label' => 'Duration', 
      'rules' => $base_rules . '|integer' 
     ), 
     array(
      'field' => 'booking', 
      'label' => 'Booking', 
      'rules' => $base_rules . '|integer' 
     ) 
    ); 
    $this->form_validation->set_rules($this->_validation_rules); 

    if ($this->form_validation->run()) { 
     // do stuff 
    }else{ 
     // prints an empty string 
     var_dump(validation_errors()); 
     exit; 
    } 

有誰知道爲什麼會出現這種情況,以及我如何得到我的錯誤?

回答

5

看跌VALIDATION_ERRORS()在你的窗體的頂部,並改變你的代碼

if ($this->form_validation->run()) { 
     // do stuff 
    }else{ 
     $this->load->view('myform'); //display your form again 
    } 

VALIDATION_ERRORS()將只在一個視圖poplated。

+5

非常感謝,雖然有一個問題 - 這是否意味着無法將驗證錯誤存儲在flashdata或其他存儲中,因此我可以在其他地方重定向?乾杯 – AaronDS

+0

@John如果我們發送一個AJAX請求會怎麼樣?當然,那麼我們需要在Controller中獲取錯誤而不是View。那麼,有沒有解決方案可以在Controller中獲取錯誤? 'validation_errors()'在Controller中不起作用。 – muaaz

1

投放形式的視圖文件的代碼頂部

echo validation_errors('<div>', '</div>'); 

然後其他改成這樣

else{ 
    $this->load->view('myform'); //display your form again 
} 
+0

不知道這個,謝謝你的貢獻。 – AaronDS

1

要完成約翰回答,如果你做了一個表格後,你可以根據你輸入的說:

<?php echo form_error('input-name'); ?> 

但是,如果你正在發出一個ajax請求(現在不是你的情況,但在未來,如果你需要的話) 你可以使用validation_errors()。

這裏的爲例:

//Important to turn that off if it's on 
    $this->output->enable_profiler(false); 

    $this->output->set_status_header('500'); 
    $this->output->set_content_type('application/json'); 

    echo json_encode(array(
     'error_msg' => validation_errors(), 
    )); 

,然後在您的客戶端可以使用這樣的迴應:

error:function(data) { 
    $("your-error-input-selector").html('').append(data.responseJSON.msg); 
} 

希望我幫助即使我1年晚。

P.S對不起,我英文破了。

+0

不工作......'validation_errors()總是返回一個空字符串。 – muaaz

+0

您是否添加了表單驗證?你有沒有運行你的驗證?我可以看看你的代碼嗎?我會很樂意幫助你! – Gabtheviking