Welcome Guest, Not a member yet? Register   Sign In
Codeigniter custom validation rules in model
#4

(01-09-2015, 10:39 AM)Narf Wrote:
(01-09-2015, 04:59 AM)[email protected] Wrote: Goal is that all data manipulation functionality should be in model.

There's a difference between validation and manipulation ...

The best approach is to get all data validate from controller once it is all good then call the save method form model. In you case
I would do something like

class user extends CI_Controller(){

function __construct(){
parent::construct();
$this->load->model('user_model); //assume that you havent auto loaded then we can load here
$this->load->library('form_validation);
}
/* Assume here is the controller for showing user form
*
*/
function index(){
//put all validation code here
$this->form_validation->set_rules('trigger_name', "trriger", 'trim|required');
$this->form_validation->set_rules('from_user', "from", 'trim|required');
$this->form_validation->set_rules('to_user', "to", 'trim|required');
$this->form_validation->set_rules('email', "email",'callback_validate_user');
//fail validation
if($this->form_validation->run()===FALSE){
$this->load->view('yourformview', array()); // option array which you can pass something to view
}
else{ // all validation ok then
$post_data =$this->input->post(NULL,TRUE); //grab all data from form submission and sanitized with XSS, this is //optional
$this->user_model->save($post_data);
}

}//end index func
//here is your call back
// I just copy your code here but you may think of passing email to user_model to check if it is valid email
// then return FALSE or TRUE accordingly
// suggesting like $this->user_model->check_email($str) in which return boolean true or false
//
public function validate_user($str){
//your code just blindly return false
$this->form_validation->set_message('email', 'Invalid user ');
return false;
}//end callback


}//end class

I hope this helps
Reply


Messages In This Thread
RE: Codeigniter custom validation rules in model - by dbui - 01-09-2015, 11:56 AM



Theme © iAndrew 2016 - Forum software by © MyBB