Welcome Guest, Not a member yet? Register   Sign In
Moving form validation callbacks to a library
#1

[eluser]DrDave[/eluser]
Sorry for all of the questions lately. Once I am up to speed hopefully I can contribute to the forum in a meaningful way.

My question of the day is regarding moving my form validation callbacks to a library. I have read the documentation and searched the forum but can't find the specific answer I'm looking for. I can't figure out how to call the callback from my form controller. Now that I have moved the callback, it is not being run at all.

I started by creating MY_form_validation.php in application/libraries and placing the simple example username_check callback from the docs in it. This is all it contains:

Code:
class MY_form_validation extends CI_form_validation {

   public function usernname_check($str)
   {
        if ($str == 'test')
        {
            $this->form_validation->set_message('username_check','The %s field can not be the word "test"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
   }

}

In my form controller, I have the rules set up in an array like so:

Code:
$config = array(
  array(
    'field'   => 'username',
    'label'   => 'Username',
    'rules'   => 'trim|required|min_length[4]|max_length[12]|callback_username_check|xss_clean'
), etc etc

When the callback was in the controller it worked fine, so I am guessing that I'm either not calling it correctly now, or it is not passing the error message back to the controller, or both.

Thanks in advance for any help!
#2

[eluser]DrDave[/eluser]
I think I answered my own question. You can't put callbacks in a library (correct me if I'm wrong), but you can extend the Validation Library and write your own functions. This is essentially what I was trying to do but I was just going about it wrong.

For anyone else who might have a question on this, I found a great tutorial <a href="http://www.scottnelle.com/41/extending-codeigniters-validation-library/">here</a>
#3

[eluser]CroNiX[/eluser]
Sure you can and you were doing it right except for your rules declaration. Once you extend the form_validation library with MY_Form_validation it becomes part of the original class, so you don't need to reference it with "callback_". Its now just a regular rule like the other native rules, so just call it "username_check" in your rules $config array instead of callback_username_check.

"callback_" is kind of a magic word reference which forces CI to look for a function/method with the same name within the controller it was called from.
#4

[eluser]DrDave[/eluser]
Ahh ok, thanks!




Theme © iAndrew 2016 - Forum software by © MyBB