Welcome Guest, Not a member yet? Register   Sign In
Should I be doing this for form validation?
#1

When I first started using CI I basically read a bunch of tutorials online. One of these tutorials (I can't remember which), had form validation rules defined in the model, which I liked because it was something I was used to doing in asp.net mvc. I've been doing this for a while, but just realised, I can't seem to find this way in the form validation docs. I think an example is clearer

Model

PHP Code:
 public $validate = array(
 
   'create_course'=> array(
 
     'course_title' => array(
 
       'field'=>'course_title',
 
       'label'=>'Course title',
 
       'rules'=>'trim|required|max_length[160]'
 
     ),
 
     'select_language' => array(
 
       'field'=>'select_language',
 
       'label'=>'Select language',
 
       'rules'=>'trim|required|integer'
 
     ),
 
     'description' => array(
 
       'field'=>'description',
 
       'label'=>'Enter course description ',
 
       'rules'=>'trim|max_length[1000]'
 
     )
 
   )
 
 ); 

Controller

PHP Code:
 public function create()
 
 {
 
   ...
 
   $validate $this->course_model->validate['create_course']; 
 
   $this->form_validation->set_rules($validate); 
 
   if($this->form_validation->run() === FALSE) {
 
     $this->render('course_create'); 
 
   }
 
   else {
 
     ....   

So I was a little worried and wanted to confirm if this is cool, or should I only stick to what's in the examples from the docs?

Another thing that got me confused was passing a bunch of arrays to set_rules was ok, but passing one array didn't work for some reason. For example, if I just wanted to update the description field and pointed to a specific array just for just that, run() always returned false

PHP Code:
 public function update_description()
 
 {
 
   ...
 
   $validate $this->course_model->validate['create_course']['description']; 
 
   $this->form_validation->set_rules($validate); 
 
   if($this->form_validation->run() === FALSE) {
 
     ... 

Have I passed the wrong thing here?

Thanks.
Reply
#2

I think there's no problem with your approach.
For the second question, validation rules should be an array of array so you should try:
PHP Code:
public function update_description()
 
 {
 
   ...
 
   $validate[] = $this->course_model->validate['create_course']['description']; 
 
   $this->form_validation->set_rules($validate); 
 
   if($this->form_validation->run() === FALSE) {
 
     ... 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB