2017-07-17 58 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); 
       } 
      ] 
     ] 
    ] 
]; 
相关问题