2012-08-03 37 views
4

什麼,我試圖做的是非常簡單(我希望)笨Form_Validation:
我試圖用Form_Validation驗證POST數據(或通過可變提供的任何數據)。
的問題是,到/我們需要做沒有實際的形式

if ($this->form_validation->run() == FALSE){ 
//validation did not pass 
}else{ 
//validation did pass 
} 

我的一套規則是這樣運行了實際驗證我:

$this->form_validation->set_rules('key', '', 'trim|required'); //simplified 

所以,我通過AJAX將數據發送到這個腳本明顯

echo $_POST['key']; //prints valid value that is sent from AJAX 

如何使用form_validation驗證$ _POST ['key']?

AJAX代碼

$("#key-inputs .short, #key-inputs .long").change(function() { 
     var key = $(this).val(); 
     var id = $(this).attr('name'); 
     var table = $(this).attr('class'); 
     var file = $('span .file').val(); 
     var data = 'NULL'; 
     $.post(file + "/edit",{ 
         id:id, 
         key:key, 
         file:file, 
         table:table}, 
         function(code, textStatus) { 
         data = code; 
     }); 
     $(this).ajaxStop(function(){ 
      if (data == 3) $(this).parent().fadeOut('slow', function() {}); //delete 
      if (data == 2) $(this).fadeOut(200).fadeIn(200); //update 
      if (data == 5) alert('not valid'); //update parameter is not valid input (depends on set_value rules) 
      //writeConsole(previous.val().outerHTML); 
     }); 
    }); 

PHP代碼//簡化

if (!$this->input->is_ajax_request()) redirect('lang/translate/keys/'.$param); 
      //do work here 
     if ($key == "") { 
      //delete key 
      $this->lang_translate_model->DeleteKey($id, $table); 
      echo 3; 
      return TRUE; 
     } 
     $this->form_validation->set_rules('key', 'key', 'trim|required|max_length[56]|xss_clean|unique_file[lang_key:'.$param.']'); 
     if ($this->form_validation->run() == FALSE){ 
      //validation did not pass 
      echo 5; 
     } 

所以我有一些(生成)的輸入,在改變我想在DB更新只有..set_rules通過。
如果輸入是空的它刪除自身(這工作正常)

SOLUTION
TRUE/FALSE表是here

if ($this->form_validation->required($key)){ 
      //validation did not pass 
      echo 5; 
} 

如果有參數來傳遞例如min_length[2];

$this->form_validation->min_length($key,'2'); 

回答

2

請參閱this。另請查看該頁面下面的註釋。

+0

這似乎工作:)非常感謝。 – Kyslik 2012-08-03 09:22:39

3

這取決於笨的版本,您正在使用

笨3.0:

可以使用set_data方法來驗證您的自定義數據

$data = array(
     'username' => 'johndoe', 
     'password' => 'mypassword', 
     'passconf' => 'mypassword' 
); 

$this->form_validation->set_data($data); 

笨2 .X:

設置$_POST值手動

$_POST'username'] = 'johndoe'; 
    $_POST['password'] ='mypassword'; 
    $_POST['passconf'] = 'mypassword'; 

常見:

的公共部分幸運的是他們都仍然使用 form_validation->run()form_validation->set_rules(<SPECIFIC ATTRIBUTE RULES>)