2017-07-17 110 views
0

基於此documentation,如何將第二個參數傳遞給規則方法?Codeigniter將額外參數傳遞給自定義驗證規則

這是我的自定義規則

public function email_exists($email, $exclude_id=NULL) 
{ 
    if ($exclude_id !== NULL) $this->db->where_not_in('id', $exclude_id); 

    $result = $this->db->select('id')->from('users')->where('email', $email)->get(); 

    if ($result->num_rows() > 0) { 
     $this->form_validation->set_message('email_exists', '{field} has been used by other user.'); 
     return FALSE; 
    } else { 
     return TRUE; 
    } 
} 

,這是我如何把它從控制器

$rules = [ 
    [ 
     'field' => 'email', 
     'label' => 'Email', 
     'rules' => [ 
      'required', 
      'trim', 
      'valid_email', 
      'xss_clean', 
      ['email_exists', [$this->m_user, 'email_exists']] 
     ] 
    ] 
]; 

$this->form_validation->set_rules($rules); 

如何傳遞第二個參數email_exists方法?

回答

0

烏斯做正確的方式(至少對於CI 2.1+),如文檔中描述:

$this->form_validation->set_rules('uri', 'URI', 'callback_check_uri['.$this->input->post('id').']'); 
// Later: 
function check_uri($field, $id){ 
    // your callback code here 
} 

如果沒有比使你的形式$exclude_id的隱藏字段的工作和直接檢查在回調通過

$exclude_id = $this->input->post('exclude_id');//or whatever the field name is 

更多here

+0

謝謝,但基於文檔,我把規則的模式,使我可以從任何控制器調用它。如果我遵循您的建議,則該規則將僅在當前控制器上可用。 – milikpribumi

0

它似乎CI不爲此提供了一種機制。我發現了幾種方法來解決這個問題。第一種方式,你可以破解文件系統(Form_validation.php)和修改一些腳本在行728

if (preg_match('/(.*?)\[(.*)\]/', $rule[1], $rulea)) { 
    $method = $rulea[1]; 
    $extra = $rulea[2]; 
} else { 
    $method = $rule[1]; 
    $extra = NULL; 
} 

$result = is_array($rule) 
    ? $rule[0]->{$method}($postdata, $extra) 
    : $rule($postdata); 

方式二,你是否可以extends CI_Form_validation核心,並在其中添加自定義規則。我在codeigniter documentation上找到了關於此的詳細信息。

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class MY_Form_validation extends CI_Form_validation 
{ 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function check_conflict_email($str, $exclude_id=NULL) 
    { 
     if ($exclude_id !== NULL) $this->CI->db->where_not_in('id', $exclude_id); 

     $result = $this->CI->db->select('id')->from('users')->where('email', $str)->get(); 

     if ($result->num_rows() > 0) { 
      $this->set_message('check_conflict_email', '{field} has been used by other user.'); 
      return FALSE; 
     } else { 
      return TRUE; 
     } 
    } 

} 

/* End of file MY_Form_validation.php */ 
/* Location: ./application/libraries/MY_Form_validation.php */ 

第三種方式,我認爲這是最好的辦法。由於skunkbad用於提供solution

$rules = [ 
    [ 
     'field' => 'email', 
     'label' => 'Email', 
     'rules' => [ 
      'required', 
      'trim', 
      'valid_email', 
      'xss_clean', 
      [ 
       'email_exists', 
       function($str) use ($second_param){ 
        return $this->m_user->email_exists($str, $second_param); 
       } 
      ] 
     ] 
    ] 
];