2011-11-18 76 views
18

我在我的登录表单中有一个函数,用于检查电子邮件和密码是否与数据库中的值匹配,如果是,则会将用户登录到系统中。创建一个自定义的代码验证规则

如果此函数返回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()) 
       { 

回答

38

你用你的规则callback_,看到callbacks,为前。

$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; 
    } 
} 

然后,您需要在情况下创建一个相应的错误验证失败来实现这一目标是扩大CodeIgniter的表单验证库

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

名称“_validate_member”会更好.. – Ivan

+0

@Ivan这是没有必要的,但可以添加可读性,谢谢 –

+6

可能不是必需的,但是一个前导下划线将阻止通过“/ controller_name/validate_member/blah”访问该方法...并且使用双下划线是完全可以接受的IMO“callback__validate_member”;) –

5

一个最好的办法。假设我们要为数据库表users的字段access_code创建一个名为access_code_unique的自定义验证程序。

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

<?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]');