Welcome Guest, Not a member yet? Register   Sign In
Form validation not running callback function
#1

[eluser]benshepherd283[/eluser]
Hello,

Before I state my problem, I would like to say that I started learning CodeIgniter yesterday so apologies in advance if I make myself look stupid

I have a model that I am using to check inputted information when a user signs up and I would like a callback function that checks if the username contains symbols but for some odd reason, I can't seem to get the callback function to work. I can't get it to be called
Here's my code:

Code:
public function create() {
  
   $this->init();
  
   $this->load->library('form_validation');
   $this->form_validation->set_rules('username','Username','required|min_length[3]|max_length[16]|is_unique['.$this->table.'.username]|trim|xss_clean|callback_validate_username');
   $this->form_validation->set_rules('password','Password','required|min_length[6]');
   $this->form_validation->set_rules('passconf','Password confirmation', 'required|min_length[6]');
  
   return $this->form_validation->run();
  
  }
  
  public function validate_username($username) {
  
   die("DEBUG"); //so I can see if it has been called
  
   if(!preg_match("/^[a-zA-Z0-9]+$/", $username)) {
    
    $this->form_validation->set_message('validate_username', 'Username must not contain symbols');
    return false;
    
   }
  
   return true;
  }
#2

[eluser]Ckirk[/eluser]
each rule for the username field will run in sequence. Can you confirm that all previous rules are running? (required, min_length, max_length etc.)
#3

[eluser]benshepherd283[/eluser]
The other rules still run, just not the callback.
#4

[eluser]Ckirk[/eluser]
Oh.... is all this code inside the model?
If so when you call for a call back I think CI expects the callback function is in the controller so try this instead:

Code:
callback_MODELNAME->validate_username

Not sure if that's the solution as my callbacks are always in my controllers. Let me know if this helps

#5

[eluser]benshepherd283[/eluser]
If I had a function in my controller called username_check for example, wouldn't that run if someone went to /controller/username_check?

Is there a better way to do this?
#6

[eluser]Ckirk[/eluser]
not if it were a private function.

prefix it with "_" and it can't be called. eg.
Code:
private function _validate_username($username)

then call it like so (note the double underscore):
Code:
$this->form_validation->set_rules('username','Username','required|min_length[3]|max_length[16]|is_unique['.$this->table.'.username]|trim|xss_clean|callback__validate_username');

#7

[eluser]benshepherd283[/eluser]
Alrighty

That works, thanks for the help.




Theme © iAndrew 2016 - Forum software by © MyBB