以编程方式使“$this->form_validation->run()”返回 false


Programmatically Make "$this->form_validation->run()" Return false

我的目标包括两个步骤

步骤 1

  • 首先检查空usernamepassword
  • 如果为空,则返回到登录表单,说明空值被发现

步骤 2

  • 未找到空值,因此通过查询数据库来检查登录名是否有效
  • 如果有效,请转到仪表板
  • 如果没有,请返回登录表单,说明登录失败

对于上述场景,我的控制器代码如下:

控制器

$this->form_validation->set_rules('userid', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
    $this->load->view('login'); // this works fine if either of one is empty
}
else
{
    // I query the database and check if valid or not
    if(<not_valid>)
    {
       // but how to pass the "Login Failed" message in this code block?
       /* I'm assuming that if I somehow make "$this->form_validation->run()" 
          return false, then the message can be passed to the view */
       $this->load->view('login');
    }
    else
    {
        $this->load->view('dashboard');
    }
}

.HTML

echo validation_errors();
<div class="form-group">
    <label for="userid" class="control-label">Enter User ID</label>
    <input type="text" id="userid" name="userid" 
       value="<?php echo set_value('userid'); ?>" class="form-control" 
       placeholder="Email Address"/>
</div>
<div class="form-group">
    <label for="password" class="control-label">Enter Password</label>
    <input type="password" id="password" name="password" class="form-control" 
       placeholder="Secret Password"/>
</div>

附言

我知道回调

,但是我将如何为两个字段(用户名和密码)触发单个回调?如果我这样做:

$this->form_validation->set_rules('userid', 'Username', 'callback_check_valid');
$this->form_validation->set_rules('password', 'Password', 'callback_check_valid');

这是否意味着我必须自己手动检查两个字段的空度?像这样的东西:?

public function check_valid($un, $pw)
{
    if(trim($un) == '' || trim($pw) == '')
    {
       return false;    
    }
    else
    {
        // check for valid login
    }
}
public function check_valid() {
    $un = $_POST['username'];
    $pw = $_POST['password'];
    if(trim($un) == '' || trim($pw) == '') {
        return false; 
    } else {
        // check for valid login
    }
}

试试这个逻辑

试试这个:

if($this->input->post()){
    $this->form_validation->set_rules('userid', 'Username', 'trim|required');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');
    if ($this->form_validation->run()){
        $username = $this->input->post('userid');
        $password = $this->input->post('password');
        if($this->check_valid($username, $password)){
            $this->load->view('dashboard');
        }else{
            $this->load->view('login');
        }
    }else{
        $this->load->view('login');
    }
}

这类似于我使用代码点火器进行登录检查的方式。

您可以将第二个修剪检查远离check_valid功能,值已经修剪