创建自定义代码编写器验证规则


Creating a custom codeigniter validation rule

我的登录表单中有一个函数,检查电子邮件和密码是否与数据库中的值匹配,如果匹配,则将用户登录到系统中。

如果这个函数返回false,我想显示一个验证错误。

我的问题是,我不确定如何去创建这个。该消息与密码和电子邮件字段都相关,因此我不想为每个输入字段设置规则,只显示一条消息。

我已经尝试使用flashdata来实现这一点,但它只在页面刷新时起作用。

我如何创建一个新的验证规则,仅为功能$this->members_model->validate_member() ??

$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', '"Password"', 'trim|required');
        if ($this->form_validation->run() == FALSE)
        {
            $viewdata['main_content'] = 'members/login';
            $this->load->view('includes/template', $viewdata);
        }
        else
        {       
                if($this->members_model->validate_member())
                {

您可以在规则中使用callback_,参见回调,例如

$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');

,并在控制器中添加方法。此方法需要返回TRUE或FALSE

function validate_member($str)
{
   $field_value = $str; //this is redundant, but it's to show you how
   //the content of the fields gets automatically passed to the method
   if($this->members_model->validate_member($field_value))
   {
     return TRUE;
   }
   else
   {
     return FALSE;
   }
}

如果验证失败,您需要创建一个相应的错误

$this->form_validation->set_message('validate_member','Member is not valid!');

实现这一点的最佳方法是扩展CodeIgniter的表单验证库。假设我们想要为数据库表users的字段access_code创建一个名为access_code_unique的自定义验证器。

你所要做的就是在application/libraries目录下创建一个名为MY_Form_validation.php的Class文件。该方法应该总是返回TRUEFALSE

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
    protected $CI;
    public function __construct() {
        parent::__construct();
            // reference to the CodeIgniter super object
        $this->CI =& get_instance();
    }
    public function access_code_unique($access_code, $table_name) {
        $this->CI->form_validation->set_message('access_code_unique', $this->CI->lang->line('access_code_invalid'));
        $where = array (
            'access_code' => $access_code
        );
        $query = $this->CI->db->limit(1)->get_where($table_name, $where);
        return $query->num_rows() === 0;
    }
}

现在您可以轻松地添加新创建的规则

$this->form_validation->set_rules('access_code', $this->lang->line('access_code'), 'trim|xss_clean|access_code_unique[users]');