2009-01-22 83 views
14

我正在使用CodeIgniter編寫我的表單驗證類。有沒有辦法讓我可以在名稱值對中得到錯誤信息?例如,在示例表單中有四個字段:user_namepassword,password_conftimezone。其中user_namepassword驗證已執行失敗後執行以下操作:CodeIgniter表單驗證 - 獲取結果作爲「數組」而不是「字符串」

$result = $this->form_validation->run(); 

如果上面的函數返回假的,我想在名稱值對錯誤類似如下:

Array 
{ 
    'user_name' => 'user name is required', 
    'password' => 'passord is required' 
} 

我真的想要形成一個JSON,我可以傳回AJAX調用。我有一個(髒)解決方案:我可以打電話驗證方法,一個個像如下:

$this->form_validation->required($user_name); 
$this->form_validation->required($password); 

是否有任何其他的方式,讓所有的錯誤信息一次在名稱值對?

編輯:我建議從其中一個答案做驗證使用jQuery:

jQuery將在客戶端驗證幫助,但對於服務器端,我使用笨驗證。

我設計它,以便:

  1. 我發佈使用AJAX的所有值。
  2. 在服務器端(PHP)進行驗證。
  3. 如果輸入有效,請執行所需的操作;否則將錯誤返回給用戶。

回答

16

我已經尋找到的笨代碼中找到一個方式自己: 我已經擴展了圖書館CI_Form_validation,如: -

class MY_Form_validation extends CI_Form_validation 
{ 
    public function getErrorsArray() 
    { 
     return $this->_error_array; 
    } 
} 

我知道,這是一個黑客,但將成爲我需要時間。我希望CodeIginter團隊很快提出一個訪問該陣列的接口。

1

看起來像代碼點火器驗證讓你在正常頁面刷新錯誤信息是不是更好使用像jquery validation plugin這將在發送表單之前完全客戶端驗證?沒有必要這樣的AJAX。

編輯: 我不建議不要做服務器端驗證,只是發佈與AJAX爲了驗證是沒有必要的,並會減少服務器命中,如果你做它的客戶端。它會優雅地降級到常規頁面刷新,並帶有錯誤或成功消息。

+3

客戶端驗證不應該是您唯一關心的問題,後端驗證更重要。 – 2009-01-22 14:24:46

+0

對,這將是愚蠢的。我沒有建議不做服務器端驗證 - 再次閱讀我的編輯和原始文章。 – roborourke 2009-01-23 11:10:13

+0

此外,有時驗證需要後端完成,例如驗證某個數據庫表(表中的唯一性) – MaxiWheat 2012-12-12 20:20:14

1

您可以在控制器

private function return_form_validation_error($input) 
{ 
    $output = array(); 
    foreach ($input as $key => $value) 
    { 
     $output[$key] = form_error($key); 
    } 
    return $output; 
} 

,然後在你的驗證方法,只需調用此創建一個私有函數,這裏是我的

public function add_cat_form() 
 
    { 
 
     $this->output->unset_template(); 
 
     $this->load->library('form_validation'); 
 
     $this->form_validation->set_rules('name', 'Name', 'required'); 
 
     if ($this->form_validation->run()) 
 
     { 
 
      if (IS_AJAX) 
 
      { 
 
       $dataForInsert = $this->input->post(); 
 
       if ($dataForInsert['parentid'] == -1) 
 
       { 
 
        unset($dataForInsert['parentid']); 
 
       } 
 
       $this->post_model->add_cat($dataForInsert); 
 
       echo json_encode('success'); 
 
      } else 
 
      { 
 
       #in case of not using AJAX, the AJAX const defined 
 
      } 
 
     } else 
 
     { 
 
      if (IS_AJAX) 
 
      { 
 
       #This will be return form_validation error in an array 
 
       $output = $this->return_form_validation_error($this->input->post()); 
 
       echo $output = json_encode($output); 
 
      } else 
 
      { 
 
       #in case of not using AJAX, the AJAX const defined 
 
      } 
 
     } 
 
    }

相關問題