codeigniter3表单验证回调函数调用不必要

时间:2017-02-07 12:26:24

标签: php codeigniter

我正在使用codeigniter 3.我在表单中有一个电子邮件字段,并在电子邮件中使用required|callback_is_email_exist rules当我将电子邮件字段留空时,它会显示回拨消息而不是必需消息。 我曾在codeigniter 2上工作过,它反复地展示了" required"消息,CI3表单验证在使用回调时不执行序列中的规则。 以下是我的代码

查看:welcome_message

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Welcome to CodeIgniter</title>
    </head>
    <body>
    <?php echo validation_errors(); ?>

    <?php echo form_open('Welcome'); ?>

    <h5>Username</h5>

    <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />

    <div><input type="submit" value="Submit" /></div>
    </form>
    </body>
    </html>

控制器:的welcome.php

public function index()
    {
         $this->load->helper(array('form', 'url'));


        $this->load->library('form_validation');

        $this->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');

                if ($this->form_validation->run() == FALSE)
                {
                     $this->load->view('welcome_message');
                }
                else
                {
                        echo 'success';
                }
    }

         public function is_email_exist($str)
        {
            //  code to check email exist in databse here
                if (is_email_exist($str)
                {
                      return TRUE;  
                }
                else
                { 
                $this->form_validation->set_message('is_email_exist', 'Email Does not exist');
                            return FALSE;
                    }
            }

预期输出

提交

电子邮件

Codeingiter 3期望按顺序执行规则。如果一个成功,则下一个执行。在这种情况下,如果我将电子邮件字段留空,则不必要地执行回调。因此它显示错误的消息。它应该显示电子邮件字段而不是电子邮件不存在。

感谢您的反馈。

1 个答案:

答案 0 :(得分:1)

我是这样做的:

创建文件:/application/libraries/MY_form_validation.php

<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
class MY_Form_validation extends CI_Form_validation
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Your custom validation
     */
    public function is_email_exist($str)
        {
            $CI =& get_instance();
            //  code to check email exist in databse here
            if ($str=='test') {
                return true;  
            }else { 
                $this->form_validation->set_message('is_email_exist', 'Email Does not exist');
                return FALSE;
            }
        }
}

/* End of file MY_form_validation.php */

/* Location: ./application/libraries/MY_form_validation.php */

在控制器中(删除回调):

...
$this->form_validation->set_rules('email', 'Email', 'required|is_email_exist');
...

在控制器删除功能中:callback_is_email_exist

但是如果你想检查电子邮件是否是唯一的:

在控制器中:

...
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]',['is_unique'=>'Email exist!']);
...
相关问题