mega-crazy
mega-crazy

Reputation: 858

Codeigniter Form Validation in Model

Hello all, this is my first CI project.

I have a simple form validation function in my model.

function verify_login()
{

    //This method will have the credentials validation
    $this->load->library('form_validation');

    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

    var_dump($this->form_validation->run());
    die;
    if ($this->form_validation->run() == FALSE) {
        //Field validation failed.  User redirected to login page
        $this->load->view('login_view');
    } else {
        //Go to private area
        redirect('home', 'refresh');
    }
}

This only works when it's in a controller but not in a model. When I try passing the variables from the controller to the function in the model, the variables get received but won't process.

Can someone enlighten me? Thank you.

Upvotes: 1

Views: 7433

Answers (4)

MERT DOĞAN
MERT DOĞAN

Reputation: 3106

If you want to use form validation library of Codeigniter in your model and want to use callback; follow this steps:

  1. first of all you must seperate rules by array.
  2. And than you may use anonymous function trick.

Example below:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class My_model extends CI_Model {

        public function check_database($var){
           return $var;
        }    
        
        public function verify_login()
        {
        
            //This method will have the credentials validation
            $this->load->library('form_validation');
        
            $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
        
        
        
        
        //edit your rule as below
        $this->form_validation->set_rules('password', 'Password', array('trim','required','xss_clean',array('check_database','callback_check_database')));
        
        //and we must show custom error for our custom function check trick
        $this->form_validation->set_message('check_database', 'This is a custom error for {field}!');
    
    //That's all folks :)
        
        
        
        
        
            var_dump($this->form_validation->run());
            die;
            if ($this->form_validation->run() == FALSE) {
                //Field validation failed.  User redirected to login page
                $this->load->view('login_view');
            } else {
                //Go to private area
                redirect('home', 'refresh');
            }
        }

Upvotes: 0

Aris Yuda Pratama
Aris Yuda Pratama

Reputation: 1

class Data_model extends CI_Model
{
public function rules()
    {
        return [
            ['field' => 'pertanyaan',
            'label' => 'pertanyaan',
            'rules' => 'required|is_unique[data.pertanyaan]'],

            ['field' => 'jawaban',
            'label' => 'jawaban',
            'rules' => 'required']
        ];
    }
}


class Datas extends CI_Controller
{
public function add()
    {
        $data = $this->data_model;
        $validation = $this->form_validation;
        $validation->set_rules($data->rules());
        if ($validation->run()) {
            $data->save();
            $this->session->set_flashdata('success', 'Berhasil disimpan');
        }

        $this->load->view("admin/data/new_form");
    }
}

Upvotes: 0

Zarathuztra
Zarathuztra

Reputation: 3251

My biggest recommendation to you is to not do validations like this in your model. If you're validating in your model it needs to be against a database value directly and not a form.

Please let me know if that solves your problem, if not please comment and I'll edit my answer.

UPDATE: Please ignore some of the above, as I was going off theory and not fact :)

I'll have to dig deeper into the CI core to get a good idea of what's wrong with this. Your code itself looks ok. Only thing I can see is that your callback may not exist in your model and only in your controller. Echoing the below I do not consider this a good use of the model.

The docs on validations

Upvotes: 1

cartalot
cartalot

Reputation: 3148

its fine to do your form validation in a model. But you want to have the validation return True or False to your controller. Not call a view. So like

// in your Model lets call it Users
function verify_login()
{    
    $this->load->library('form_validation');

    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

    if ($this->form_validation->run() == FALSE) {
       return FALSE ; 
    } else {
       return TRUE; 
    }
}

// Your callback function 


 // in Controller 
function verify(){

if( $this->users->verify_login() == FALSE ){  
// $this->errormessage will be available in any view that is called from this controller
$this-errormessage = "There was an error with your Log In. Please try again." ; 
$this->showLogin() ; } 

else { 
// set a session so you can confirm they are logged in on other pages
$this->setLoginSession($this->input->post('username', TRUE)) ; 
$this->showUserHome(); } 
}

Another thing to think about -- often people know their user name but mess up their password. So if you check for them separately you can adjust the error message accordingly. And if you check for user name and there are no results -- you don't need to check for password and in the error message you can tell them there is no user by that name.

Upvotes: 6

Related Questions