1

我想使用 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;
}

谢谢你。

4

3 回答 3

3

文档中

“注意:这些规则也可以称为离散函数。例如:$this->form_validation->required($string);”。

于 2013-01-05T14:12:00.203 回答
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
}

}

之后,您可以回显视图中的错误(如果有)。

于 2013-01-05T14:39:30.193 回答
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;
}
于 2017-04-10T13:27:19.163 回答