Skip to content

Validation within models in CodeIgniter?

Last updated on January 17, 2018

In general, we write all validation rules in Controllers, This is perfectly fine, but can lead to a large amount of validation code within your controllers.Let’s have a look at how we can shift some of the validation logic into our models instead.

First Create Our Model


class Test_model extends CI_Model {

public $rules = array(
		'name' => array(
			'field' => 'name', 
			'label' => 'Name', 
			'rules' => 'trim|required|xss_clean'
		),
		'message' => array(
			'field' => 'message', 
			'label' => 'Message', 
			'rules' => 'trim|required|xss_clean'
		),
	);

}

Now Create a Controller : controller/test.php.
I am writing inline comments in the code, just go through it and let me know if you have confusion or further improvement in coding or tutorial.

class Test extends CI_Controller {
   public function index() {
      // load the model to get rules property 
      $this->load->model('test_model');
	
     // get rules array from the model
     $rules = $this->test_model->rules;
    // set validation rules	
     $this->form_validation->set_rules($rules);	
     // Process the form
      if ($this->form_validation->run() == TRUE) {
         // do something 
      } else {
        // do something
      } 		
   }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments