代码之家  ›  专栏  ›  技术社区  ›  asprin

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

  •  0
  • asprin  · 技术社区  · 6 年前

    在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会忽略之前的规则(例如 required , min_length 等等)在这种情况下?如果我的假设是正确的,方向是从左到右的,即使其中一条失败了,它也不会移动到下一条规则。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Abhishek Sharma    6 年前

    在你的口袋里试试这个 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
    }
    
        2
  •  0
  •   asprin    6 年前

    我将发布我采取的方法。但我会接受阿披实的回答,因为他把我引向了正确的方向。有点遗憾的是,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;
        }   
    }
    
    推荐文章