2013-01-05 30 views
1

我想使用codeigniter form_validator庫驗證表單。我該如何驗證codeigniter中的ajax表格

問題是數據來自ajax,所以我不明白代碼應該如何。

public function register(){ 
    $this->load->library('form_validation'); 
    $json = $_POST['data']; 
    $json = json_decode($json); 
    $data = get_object_vars($json); 

    $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean'); 
    if($this->form_validation->run()){ 
     echo 'asdf'; 
    } else { 
     echo 'xyz'; 
    } 

} 

您可以看到$ _POST超全局數組有一個$ data數組。我怎樣才能驗證$ data數組並返回一個帶有json編碼數組的狀態和錯誤消息的響應?

這是我如何使用AJAX發送數據的方式:

function register(){ 
    var site_url = $("#site_url").val(); 
    var post_url = site_url+"index.php/ajax/register"; 

    var details = { }; 

    details.username = $("#username").val(); 
    details.password = $("#password").val(); 
    details.rpassword = $("#rpassword").val(); 
    details.country = $("#country").val(); 
    details.postal_code = $("#postal_code").val(); 
    details.email = $("#email").val(); 
    details.date_of_birth = $("#date_of_birth").val(); 


    var json = JSON.stringify(details); 

    $.post(post_url, {'data': json}, function(data){ 
     alert(data); 
     //data = JSON.parse(data); 



    }); 

    return false; 
} 

謝謝。

+0

你是如何從視圖發送數據的數據,你可以展示AJAX調用? –

+0

我編輯了第一篇文章。我已經添加了ajax代碼。 –

+0

爲什麼要序列化數據並將其作爲JSON發送?爲什麼不使用POST字段? –

回答

2

好的還沒有測試過,但它應該工作。

首先不要打擾發送數據到你的控制器作爲json,只是發送它作爲一個普通的發佈請求。

$.post(post_url, {'data': details}, function(data){ 

然後在控制器中,您可以像處理任何表單驗證一樣處理驗證。

public function register(){ 
$this->load->library('form_validation'); 
$this->form_validation->set_rules($this->input->post('username'), 'Username', 
'trim|required|min_length[5]|max_length[12]|xss_clean'); 
if($this->form_validation->run()==FALSE){ 
    $errors = 'Username error here'; 
} 
//You can iterate through any other validation rules building the $errors 
//variable then pass them back to the view with: 

if(isset($errors)) 
{ 
    print json_encode(array("status"=>"error", "message"=>$errors)); 
} else { 
    /execute pass code here 
} 

} 

之後,你可以在視圖中回顯錯誤,如果有的話。

+0

它不起作用。我不知道$ this-> validaton_form對象知道如何在$ _POST ['username']的$ _POST數組中查找。 '$ this-> input-> post ['username]''在那裏是什麼?代碼需要逃脫工作。 –

+1

這就是codeigniter處理$ _POST對象的方式。驗證的第一個參數是要驗證的內容,第二個參數是如果出現錯誤時要返回給用戶的用戶友好名稱,第三個參數是要檢查的內容。我也注意到驗證行中有一個錯字。現在就試試。 –

+0

grrr,另一個錯字。我使用自定義輸入處理程序,$ this-> input-> post not square上的圓括號。 –

3

the documentation

「注意:這些規則也可以被稱爲爲離散功能。例如函數:$ this-> form_validation->需要($字符串);」。

0

有一種驗證不是來自POST/GET請求的數據的方法。 我覺得這個環節應該有所幫助:https://www.codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post

我測試的是來自解碼php://input

$filters_obj = json_decode(file_get_contents('php://input')); 
$this->form_validation->set_data($filters_prop_arr); 
$this->form_validation->set_rules('email', 'Full Name', 'required'); 

if ($this->form_validation->run() == false) { 
    var_dump('not workin'); 
    return false; 
}