As always, when talking about forms we also talk about validation. For a long time I’ve validated the forms inside the controllers because it is fast and simple – no more browsing between files.
But after a while you find yourself having a controller which is becoming more complex and bigger. So why not keep at least the validation rules somewhere else?
One solution would be to keep all the validation rules inside a config file, and organize the rules into “groups”. I will talk about this method in another post.
The other solution would be to put the validation rules inside the model, which, in my opinion would make more sense, considering that every form element is actually a column inside your database tables.
class Contacts_model extends CI_Model
public $rules = array(
'first_name' => array('field'=>'first_name','label'=>'First name','rules'=>'trim|required|xss_clean'),
'last_name' => array('field'=>'last_name','label'=>'Last name','rules'=>'trim|xss_clean'),
'email' => array('field'=>'email','label'=>'Email','rules'=>'trim|valid_email|required|xss_clean'),
'password' => array('field'=>'password','label'=>'Password','rules'=>'trim|required|xss_clean')
'signinform'=>(/*...some other rules for another form...*/);
//.... next come the methods of the model...
As you can see, you can make an array that contains different rules depending on the forms that are used. The array is public, so that it can be accessed directly by the controller. Regarding password, there will be alot of people arguing that I can’t just verify plain password against the database and that the password needs to be encrypted. Yet this is not the scope of this post. I only wanted to give an example about how to keep the rules inside the model.
Now, going to the controller, you simply call the rules:
class Contacts extends CI_Controller
public function signup()
$rules = $this->contacts_model->rules['signupform'];
if($this->form_validation->run() === FALSE)
// if the user signed up, do whatever...
I won’t go and make the view, that not being the point of this post. The only thing I hope you understand is that every form element must be named exactly like the keys inside the array we defined in the model (first_name, last_name, email, password, etc.).