1

I doing form validation in CodeIgniter using Form Validation Library and my custom callbacks.

public function insert_user()
{
    if($this->input->post('submit')) {
        // load form validation library
        $this->load->library('form_validation');

        // configurations
        $config = array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'required|callback_username_check'
            )
        );
        $this->form_validation->set_rules($config);

        // .... continue ....
    }   
}

When method is public, it is working as expected.

public function username_check($username)
{
    // do some stuffs here
}

When I make method as private, it is not working.

private function username_check($username)
{
    // do some stuffs here
}

Why callbacks from private methods are not working?

Why I need this?

Public methods in CodeIgniter controllers are accessible by URLs like an example above

http://example.com/controller_name/username_check/blabla

I don't want callback methods accessible publicly.

Madan Sapkota
  • 25,047
  • 11
  • 113
  • 117
  • You need to read a little bit about visiblity inside the PHP documentation .. http://php.net/manual/en/language.oop5.visibility.php – Svetoslav Apr 18 '13 at 09:13
  • You are not calling it inside the same class .. :) Your Form validator is accessing current class function which should be public.. – Svetoslav Apr 18 '13 at 09:25
  • See my comment in @Svetlio answer -- either of those solutions would be suitable. – Aken Roberts Apr 19 '13 at 01:39

2 Answers2

2

The callback function must be public. Codeigniter Form validation class access your function at current controller so it may not be private..

To go around your problem you may think about extending you CI_Form_validation class with a My_form_validation..

class MY_Form_validation extends CI_Form_validation
{
    public function __construct()
    {
       parent::__construct();
    }

    function username_check($str)
    {
      /* your code */
    }

} 

Then in your validation you must set only..

            'rules' => 'required|username_check'
Svetoslav
  • 4,686
  • 2
  • 28
  • 43
  • 5
    Another option would be to prepend an underscore to the callback function name, which is a little CI-specific "trick" to make a public method unaccessible from the URI. `username_check` would become `_username_check`, and the callback name would use double underscores: `callback__username_check`. – Aken Roberts Apr 19 '13 at 01:38
0

Private function can only be accessed by an object of the class. This function are visible in its own class only. Read more about variable/function scope here

Community
  • 1
  • 1
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45