Hi I hope you can help me with this. I have seen many of the same questions on this issue and none of them works for me.
I am using Codeigniter 2.2.2 and trying to create form validation in model so it can be accessible by multiple controllers. The form validation was not able to return correctly on custom callbacks declared in the model.
// in Model
function validateErrors() {
$rules = array(
array('field'=>'username', 'label'=>'User', 'rules'=>'trim|required|callback_userPrefix'),
array('field'=>'password', 'label'=>'Password', 'rules'=>'trim|required|callback_passwordNotEmpty'),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$errors = array();
foreach ($rules as $r)
$errors[$r['field']] = $this->form_validation->error($r['field']);
return $errors;
}
return false;
}
public function userPrefix() {
$find = 'user_';
if (strpos($this->input->post('username'), $find) != 0) {
$this->form_validation->set_message('userPrefix', 'Username not allowed.');
return false;
}
return true;
}
public function passwordNotEmpty() {
// not the actual callback just an example
if (empty($this->input->post('password'))) {
$this->form_validation->set_message('passwordNotEmpty', 'Password cannot be blank.');
return false;
}
return true;
}
so it can be accessed in Controller like:
// in Controller
if ($this->input->post()) {
$this->load->model('ModelName','model1', true);
$validation_errors = $this->model1->validateErrors();
if ($validation_errors === false) {
// continue saving record
} else {
print_r($validation_errors); exit;
}
}
I wanted to create form validation every user login. But since multiple controllers make use of the same validation, I declared the validation and their custom callbacks in the model to minimize coding length in controllers (hopefully minimize).
Also, this answer says you can do the form validation in the model (also showing callbacks declared in model supposedly work). I tried that but wouldn't work for me.
Can anyone help me in this? Thank you very much!