简体   繁体   中英

form validation error in Codeigniter

I've been following this tutorial by Envato on Tutplus: https://tutsplus.com/course/build-a-cms-in-codeigniter/ . I'm at the part at which I want to validate login form. My problem is I can't use my form validation rule in login system. My code is given below:

user_m.php

<?php 
  class User_M extends MY_Model {

public $rules = array(  // I can't use this rules in my controller
   'email' => array(  // for email 
    'field' => 'email',
    'label' => 'Email',
    'rule'  => 'trim|required|valid_email|xss_clean'
    ),
    'password' => array(  // for password
    'field' => 'password',
    'label' => 'Password',
    'rule'  => 'trim|required'
     )
);

}

user.php

 <?php 

class User extends Admin_Controller {

public function __construct()
{
    parent::__construct();
}

public function login()
{   
   // Set form
   $rules = $this->user_m->rules; // get the value from user_m model and it works well
       // this is not works. this is my problem
   $this->form_validation->set_rules($rules);  

       // if we use this comment code then it works
   //$this->form_validation->set_rules('email', 'Email', 'rim|required|valid_email|xss_clean'); 
   // $this->form_validation->set_rules('password', 'Password', 'required');

   // Process form
   if ( $this->form_validation->run() == TRUE )  { // show the error msg if form problem occurs 
       // We can login and redirect

    }

}

You may try this (set the rules in your controller before you call form_validation->run() function)

public function login()
{
    $this->form_validation->set_rules('email', 'Email',  'trim|required|valid_email|xss_clean');
    $this->form_validation->set_rules('password', 'Password',  'trim|required');
    if ( $this->form_validation->run() )  {
        // validation passed
    }
    else {
        // validation failed
    }
}

You make sure that you have write form_error('email'); and form_error('password'); below email and password text boxes. Please call login view if validation error occurs.

public function login()
{
   $this->form_validation->set_rules('email', 'Email',  'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('password', 'Password',  'trim|required');
   if ($this->form_validation->run() == FALSE)
        {
           **$this->load->view('login view path');**
        }else{write other code of redirect or any.....} 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM