【问题标题】:CodeIgniter num_rows() not working?CodeIgniter num_rows() 不工作?
【发布时间】:2012-12-02 01:08:52
【问题描述】:

好吧,我不知道什么不起作用。我知道我的表单验证肯定是有效的,因为我的所有其他功能都可以正常工作,但是我正在设置消息,无论是真还是假,它们都没有出现,所以我觉得它正在跳过验证规则......这很奇怪...... .

$this->form_validation->set_rules('region', 'required|valid_region');

我的库文件夹中 MY_Form_validation.php 中的规则。首先加载库。正如我所说,我的所有其他验证都可以正常工作,例如我的 reCaptcha 和所有内容。

function valid_region($str) {
        $this->load->database();
        if($this->db->query('SELECT id
                FROM region
                WHERE name = ?
                LIMIT 1', array($str))->num_rows() == 0) {
            //not a valid region name
            $this->set_message('valid_region', 'The %s field does not have a valid value!');
            return false;
        }

        $this->set_message('valid_region', 'Why is it validating?');
    }

不会设置任何消息,所以我觉得没有任何验证!

【问题讨论】:

标签: php codeigniter


【解决方案1】:

set_rules() 函数有 3 个参数

  1. 字段名称 - 您为表单字段指定的确切名称。
  2. 此字段的“人”名,将插入到错误消息中。 例如,如果您的字段名为“用户”,您可能会给它一个人 “用户名”的名称。注意:如果您希望字段名称为 存储在语言文件中,请参阅翻译字段名称。
  3. 此表单域的验证规则。

您将验证规则作为第二个参数。这就是验证未运行的原因。试试这个:

$this->form_validation->set_rules('region', 'Region', 'required|valid_region');

【讨论】:

    【解决方案2】:

    而不是

    $this->form_validation->set_rules('region', 'required|valid_region');
    

    试试

    $this->form_validation->set_rules('region', 'required|callback_valid_region');
    

    当使用自定义验证规则时,你应该使用

    回调来添加函数名。

    更新

    并使用

    $this->form_validation->set_message
    

    而不是

    $this->set_message
    

    function valid_region

    验证成功时使用return true

    【讨论】:

    • @Peanut 正在扩展核心验证类,验证功能已在扩展类MY_Form_validation 中声明。所以他不必在函数名前加上callback_
    【解决方案3】:
    $this->form_validation->set_rules('region', 'Region', 'required|valid_region');
    
    function valid_region() {
        $str = $this->input->post('name_of_input');
        $this->load->database();
        if($this->db->query('SELECT id
                FROM region
                WHERE name = ?
                LIMIT 1', array($str))->num_rows() == 0) { // why compare "=" between `name` field and array() ?
            //not a valid region name
            $this->form_validation->set_message('valid_region', 'The %s field does not have a valid value!');
            return false;
        }
    
        $this->form_validation->set_message('valid_region', 'Why is it validating?');
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2014-06-26
      • 2014-04-15
      相关资源
      最近更新 更多