2012-12-14 47 views
0

好吧,我不知道什么是不工作。我知道我的表单验证工作正常,因为我所有的其他函数都能正常工作,但我设置的消息是否为真或假,并且没有一个显示出来,所以我觉得它正在跳过验证规则,这很奇怪。 。CodeIgniter num_rows()不起作用?

$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?'); 
    } 

无消息都会将让我有一种感觉,没有什么是验证!

+1

http://stackoverflow.com/questions/8181779/creating-a-custom-codeigniter-validation-rule –

回答

3

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'); 

你应该使用

回调预先设置的功能名称。

UPDATE

并使用

$this->form_validation->set_message 

代替

$this->set_message 

function valid_region

使用return true当验证是全成

+1

@Peanut被扩展核心验证类和验证功能有已在扩展类“MY_Form_validation”中声明。所以他不必用'callback_'来预先设置函数名称 – Stanley

0
$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; 
}