Codeigniter:在转到控制器之前验证数据

时间:2017-02-02 12:26:58

标签: javascript php jquery codeigniter

我通过单击“提交”按钮验证数据,然后再次加载视图。我想在加载控制器之前只显示页面上的错误。它不是表单验证。它只是一种数据验证。

2 个答案:

答案 0 :(得分:2)

我认为你可以使用AJAX进行验证。

答案 1 :(得分:0)

in view page

    <script type="text/javascript">
    $(document).ready(function() {
        /// make loader hidden in start
    $('#loading').hide();
     $('#email').blur(function(){
        var email_val = $("#email").val();
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        if(filter.test(email_val)){
            // show loader
            $('#loading').show();
            $.post("<?php echo site_url()?>/user/email_check", {
                email: email_val
            }, function(response){
                $('#loading').hide();
                $('#message').html('').html(response.message).show().delay(4000).fadeOut();
            });
            return false;
        }
    });

    });  
</script>

in controller function 

    public function email_check()
    {
        // allow only Ajax request    
        if($this->input->is_ajax_request()) {
        // grab the email value from the post variable.
        $email = $this->input->post('email');
        // check in database - table name : tbl_users  , Field name in the table : email
        if(!$this->form_validation->is_unique($email, 'tbl_users.email')) {
        // set the json object as output                 
         $this->output->set_content_type('application/json')->set_output(json_encode(array('message' => 'The email is already taken, choose another one')));
            }
        }
    }