表单验证set_message未在codeigniter中显示任何错误

时间:2016-07-29 05:54:13

标签: php forms codeigniter validation

我是codeigniter的新手。我现在创建了一个登录页面,如果用户输入了错误的凭据,我想显示登录详细信息错误或登录无效的错误消息。我不知道我在哪里做错了但当我输入错误的凭据时页面刷新没有任何错误消息

function login_user() {
  // Create an instance of the user model
  $this->load->model('user_m');

  // Grab the email and password from the form POST
  $username= $this->input->post('username');
  $pass  = $this->input->post('password');
  $this->form_validation->set_rules('username', 'Username', 'required|trim');

  $this->form_validation->set_rules('password', 'Password', 'required|trim');
  $this->load->helper('security');
  if($this->form_validation->run() == FALSE){
      $this->load->view('login');
  }

  if( $username && $pass && $this->user_m->validate_user($username,$pass)) {
      // If the user is valid, redirect to the main view
      redirect('/dashboard');
  } else {
      // Otherwise show the login screen with an error message.
      $this->form_validation->set_message('login_user','Wrong email, password combination.');
        $this->load->view('login');
  }

}

在我看来,我使用以下行显示错误

<?php echo validation_errors(); ?>

&#34;用户名和密码字段是必需的&#34;错误正常,但无效登录无效

1 个答案:

答案 0 :(得分:2)

我认为问题是最后一段代码片段的ELSE部分。所以你写了这样的东西。

简短定义

$this->form_validation->set_message()

仅在验证规则失败时才有效。所以我假设您输入了usernamepassword错误,但您填写的是required逻辑。所以form_validation通过了这个测试用例。 所以将$this->form_validation->set_message()更改为以下内容:

替换

if( $username && $pass && $this->user_m->validate_user($username,$pass)) {
  // If the user is valid, redirect to the main view
  redirect('/dashboard');
} else {
  // Otherwise show the login screen with an error message.
  $this->form_validation->set_message('login_user','Wrong email, password combination.');
    $this->load->view('login');
}

if( $username && $pass && $this->user_m->validate_user($username,$pass)) {

      // If the user is valid, redirect to the main view
      redirect('/dashboard');

  } else {

      // Otherwise show the login screen with an error message.

      $this->session->set_flashdata('authError', 'Username or Password Invalid !!');
      $this->load->view('login');
  }

VIEW页面上写下这样的内容:

替换

<?php echo validation_errors(); ?>

<?php if( $this->session->flashdata('authError') )
{
   echo $this->session->flashdata('authError');
}?>