弹出登录时的Codeigniter表单验证

时间:2014-04-15 20:03:04

标签: php codeigniter

我想在弹出的登录窗口中使用CodeIgniter上的表单验证库,当发生错误时我想在弹出窗口中回显验证错误。

if ($this->form_validation->run()==FALSE){
    $this->load->view("header");
    $this->load->view("menu");
    $this->load->view("content");
}

因为发生错误时视图会重新加载并且弹出窗口正在关闭 有没有办法设法在发生错误时打开弹出窗口?

2 个答案:

答案 0 :(得分:1)

对于从表单验证返回,您可以执行以下操作:

        $this->output->set_output(json_encode([
            'result' => 0,
            'error' => $this->form_validation->error_array()
        ]));

        return false;
    }

它会返回你的要求和错误,然后在jQuery你会做这样的事情:

<!-- Javascript POST -->
<script type="text/javascript">
    $(function() {

        $("#login_error").hide();
        // Check the login form, so your form name may vary
        $("#login_form").submit(function(evt) {
            evt.preventDefault();
            var url = $(this).attr('action');
            var postData = $(this).serialize();

            // Grab the post data
            $.post(url, postData, function(o) { 
                if (o.result == 1) {
                    // Redirect for successful loging
                    window.location.href = '<?=site_url('pageheretogoto')?>';
                } else {

                $("#login_error").show(); // Show your popup window, I'm showing a div here of #login-error
                var output = '<ul>'; // Format the output into a list
                for (var key in o.error) {
                    var value = o.error[key];
                    output += '<li>' + value + '</li>';
                }
                output += '</ul>';
                $("#login").html(output); // Modify the html output for the #login div which you would probably change it to your pop-up.
                }

            }, 'json');

        });

    });
</script>

您需要确保修改div名称,但这应该为您提供了一个很好的起点1)没有页面刷新和2)将内容放在您想要的位置。该示例不使用弹出窗口或模态框,但您可以轻松地对其进行调整。

答案 1 :(得分:0)

只需使用jQuery.validate()并匹配相同的规则集,您希望它的工作方式就太复杂了。您必须提交表单,刷新页面,然后在出现错误时打开弹出窗口。这有点......错了。

参考:http://jqueryvalidation.org/

相关问题