回调函数忽略其他验证规则并首先执行

时间:2019-11-28 03:55:47

标签: php codeigniter

在HTML表单上,我有一个字段,例如:

<?php
     $token = array(
       'name'          => 'pc_token',
       'id'            => 'pc_token',
       'class'         => 'form-control'           
       );
     echo form_input($token, set_value('pc_token')); ?>

在字段上设置的验证规则是:

$this->form_validation->set_rules(
    'pc_token', 'Token number', 'trim|required|min_length[5]|max_length[12]|callback_token_exists',
     array(
       'required'      =>  'You have not provided %s.',
       'token_exists'  =>  'The %s is not valid. Please recheck again'                 
       )
     );

这是回调函数

public function token_exists($key)
{        
    $this->load->model('tokens');
    return $this->tokens->IsValidToken($key); // will return true if found in database or false if not found
}

这里的问题是,当我将pc_token字段保留为空/空白并提交表单时,我没有在屏幕上看到预期的错误消息。

电流输出

  

令牌编号无效。请再次检查

预期产量

  

您尚未提供令牌编号

在这种情况下,为什么CI会忽略先前的规则(例如requiredmin_length等)?如果我的假设正确,则方向是从左到右,即使一个方向失败,也不会移至下一条规则。

2 个答案:

答案 0 :(得分:1)

在您的callback function

中尝试一下

检查empty

public function token_exists($key='')
{   

  if(empty($key)){
         $this->form_validation->set_message('token_exists', 'The {field} field is   required.');
         return FALSE;
   }else{
      $this->load->model('tokens');
      return $this->tokens->IsValidToken($key); 
    }

// will return true if found in database or false if not found
}

答案 1 :(得分:0)

我将发布我采用的方法。但是我会接受阿比舍克的回答,因为他带领我朝着正确的方向前进。 CI3没有解决这个问题,这让我有些遗憾,因此我不得不使用其他方法。

因此,验证规则变为:

$this->form_validation->set_rules(
        'pc_token', 'Token number', 'callback_token_exists'
     );

然后回调函数变为:

public function token_exists($key)
{
    if(trim($key) == "" || empty($key))
    {
        $this->form_validation->set_message('token_exists', 'You have not provided %s.');
        return FALSE;
    }
    else if(strlen($key) < 5)
    {
        $this->form_validation->set_message('token_exists', '%s should be at least 5 characters long.');
        return FALSE;
    }
    else if(strlen($key) > 12)
    {
        $this->form_validation->set_message('token_exists', '%s cannot be greater than 12 characters long.');
        return FALSE;
    }
    else
    {
        $this->load->model('tokens');
        $isValid = $this->tokens->IsValidToken($key);
        if(! $isValid)
        {
            $this->form_validation->set_message('token_exists', 'You have not provided %s.');           
        }

        return $isValid;
    }   
}