On the HTML form, I have a field such as:
<?php $token = array( 'name' => 'pc_token', 'id' => 'pc_token', 'class' => 'form-control' ); echo form_input($token, set_value('pc_token')); ?>
The validation rules set on the field are:
$this->form_validation->set_rules( 'pc_token', 'Token number', 'trim|required|min_length[5]|max_length[12]|callback_token_exists', array( 'required' => 'You have not provided %s.', 'token_exists' => 'The %s is not valid. Please recheck again' ) );
And here is the function for the callback
public function token_exists($key) { $this->load->model('tokens'); return $this->tokens->IsValidToken($key); // will return true if found in database or false if not found }
The problem here is that when I keep the pc_token
field empty/blank and submit the form, I don’t get the expected error message printed on screen.
Current Output
The Token number is not valid. Please recheck again
Expected Output
You have not provided Token number
So why does CI ignore the previous rules (such as required
, min_length
etc) in this case? If my assumption is correct, the direction is left to right and if even one fails, it does not move to the next rule.
Advertisement
Answer
try this in your callback function
check for empty
public function token_exists($key='') { if(empty($key)){ $this->form_validation->set_message('token_exists', 'The {field} field is required.'); return FALSE; }else{ $this->load->model('tokens'); return $this->tokens->IsValidToken($key); } // will return true if found in database or false if not found }