创建自定义codeigniter验证规则

hai*_*ets 22 php validation codeigniter

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

如果此函数返回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())
                {
Run Code Online (Sandbox Code Playgroud)

Dam*_*rsy 43

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

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

并在控制器中添加该方法.此方法需要返回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;
   }
}
Run Code Online (Sandbox Code Playgroud)

然后,您需要在验证失败时创建相应的错误

$this->form_validation->set_message('validate_member','Member is not valid!');
Run Code Online (Sandbox Code Playgroud)

  • 可能没有必要,但是前导下划线将阻止通过"/ controller_name/validate_member/blah"访问该方法...并且使用双下划线是完全可以接受的IMO"callback__validate_member";) (6认同)
  • 用于命名回调函数的双下划线__方案的+1,因为函数变得不可访问并返回404.更多是这样,因为`private`函数不适用于回调. (2认同)

BoC*_*ill 9

实现这一目标的最佳方法是扩展CodeIgniter的表单验证库.假设我们要创建一个以数据库表access_code_unique字段命名的自定义验证器.access_codeusers

您所要做的就是创建一个MY_Form_validation.phpapplication/libraries目录中命名的类文件.该方法应始终返回TRUEORFALSE

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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