Codeigniter中的表单验证:使用set_rules检查模式窗口中的文本输入


Form Validation in Codeigniter: using set_rules to check text input from a modal window

我正在尝试使用Codeigniter的表单验证来检查从模式窗口输入的文本与数据库中已有的文本是否冗余。我似乎无法深入了解Codeigniter的set_rules来了解发生了什么。我希望你们中的一个编码动物能帮助我。

Ajax将文本发送到Controller中的一个函数,该函数将其作为$value获取,然后在Controller中,我想检查这个字符串是否已经在DB的table.field中,如果是(否),则将$unique=false(true)发送回jQuery。问题是不管数据库中有什么,set_rules语句总是返回true。

这是控制器:

public function change_options()
{
    # Receives and sends back user-entered new option and adds it to database

    # Get strings from ajax in view
    $value = $_POST['new_option'];
    $value_class = $_POST['new_option_class'];
    //echo $value_class; die;
    #Make array to send to model
    $value_array = array('Options' => $value);
    # Make sure option is unique
    $this->load->library('form_validation');
    //$this->form_validation->set_rules('Options', 'Option', 'is_unique['.$value_class.'.Options]');    
    $this->form_validation->set_rules('add-new-submit', 'Option', 'is_unique['.$value_class.'.Options]');    <---- This is always true
    if ($this->form_validation->run() == TRUE) // Only add new option if it is unique
    {
        # Add new option to dropdown in database
        $this->load->model('data_model');
        $this->data_model->add_option($value_class, $value_array);  
        $unique = true;         
    }
    else 
    {           
        # Send string back to view via ajax
        $unique = false;
    }                       
    echo json_encode(array($value, $unique));           
}

对于set_rules的第一个槽,我已经尝试了我能想到的一切:"Options"、"add new text"、"add new submit"(后两个都是模态html中的名称)$value_class(这是有问题的表单元素的id)。以下是完整性的模式:

  <!-- add-new field -->
  <div class="modal small hide fade" id="add-new" tabindex="-1" role="dialog" aria-labelledby="add-new-fieldLabel" aria-hidden="true">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">√ó</button>
        <h3 id="add-new-fieldLabel">Add New Field</h3>
      </div>
      <div class="modal-body">
          <p>Would you like to add a new item?</p>
          <input type="text" id="add-new-text" name="add-new-text" placeholder="Type the new option">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success" id="add-new-submit" name="add-new-submit"/>Add</button>
      </div>
 </div><!-- /add-new field -->

有人看到发生了什么事吗?

我想好了如何做到这一点,并在AJAX中发布了代码,显然没有发布或接收。无需使用表单验证!