簡體   English   中英

我如何在Codeigniter中驗證Ajax表單

[英]How can I validate a ajax form in codeigniter

我想使用codeigniter form_validator庫驗證表單。

問題是數據來自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;
}

謝謝。

文檔中

“注意:這些規則也可以稱為離散函數。例如:$ this-> form_validation-> required($ string);”。

好的,還沒有測試過,但是應該可以。

首先,甚至不必費心將數據作為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
}

}

之后,您可以在視圖中回顯錯誤(如果有)。

有一種方法可以驗證不是來自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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM