CodeIgniter Forums
Codeigniter Passing Extra Parameters to Custom Validation Rule - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: General Help (https://forum.codeigniter.com/forum-24.html)
+--- Thread: Codeigniter Passing Extra Parameters to Custom Validation Rule (/thread-68482.html)



Codeigniter Passing Extra Parameters to Custom Validation Rule - sentinel - 07-17-2017

According to this documentation, how can I pass second parameter to the rule method?

This is my custom rule


PHP Code:
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() > ) {
 
       $this->form_validation->set_message('email_exists''{field} has been used by other user.');
 
       return FALSE;
 
   } else {
 
       return TRUE;
 
   }


and this is how i call it from controller


PHP Code:
$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); 

How can I pass second parameter to email_exists method?


RE: Codeigniter Passing Extra Parameters to Custom Validation Rule - skunkbad - 07-17-2017

Maybe something like this:


PHP Code:
$second_param 'whatever';

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



RE: Codeigniter Passing Extra Parameters to Custom Validation Rule - sentinel - 07-17-2017

(07-17-2017, 12:07 PM)skunkbad Wrote: Maybe something like this:


PHP Code:
$second_param 'whatever';

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

It works. Thanks a lot sir.