【问题标题】:How to validate many fields combined in Codeigniter?如何验证 Codeigniter 中组合的多个字段?
【发布时间】:2010-11-17 07:06:00
【问题描述】:

是否有一种创造性且简单的方法可以同时检查多个表单字段。

我有一个动态生成字段的表单,每个字段都有一个唯一的 ID。

事情是提交所有字段都不是必须的,但提交之前必须至少填写一个字段。

有没有办法在 Codeigniter 中做到这一点,或者我将如何有效地验证这一点。

我知道可以单独检查每个字段,但我正在寻找一种更简洁的方法。

我希望你们清楚。谢谢。

【问题讨论】:

  • 您的输入字段是如何命名的?
  • a prefix 后跟 timestamp 表示日期范围内的日期。

标签: php codeigniter


【解决方案1】:

试试这个:

$_POST['data_you_want_to_validate_together'] = $_POST['first_field'] . $_POST['second_field'];
$this->form_validation->set_rules('data_you_want_to_validate_together','Some Data', 'required|callback_some_function');

现在您可以通过以下方式获取数据:

echo $this->input->post('data_you_want_to_validate_together');

【讨论】:

    【解决方案2】:

    现在,我有一个自定义函数,它将批量检查表单上的每个提交,以确保它符合一组规则。我认为将我的表单设置为 html 数组 (data[]),在代码点火器中检索它,然后使用 CI callback_ 验证功能确保一切正常。它看起来很复杂,所以我还没有完全理解它,但也许这可以让你的轮子转向正确的方向。

    编辑:

    $this->load->library('form_validation');
    
    // If there is any posted data, then we should assign it to our $post_data array.
    
    $post_data = $this->input->post('project_data');
    if (empty($post_data)) {die('empty form');}
    
    // Now, we are ready to validate the incoming data.
    // We will send the data through a callback function which will check to make sure it is valid.
    // If it is not valid, the callback function will trigger a codeigniter validation error.
    
    // Let's temporarily remove any commas from the submission data to avoid delimiter confusion when sending it through the callback
    
    $post_data = str_replace(",", "DELIMITEDCOMMA", $post_data);
    
    $post_data_str = http_build_query($post_data);
    $this->form_validation->set_rules("project_data[errors]", 'Errors', "required|callback__validate_project_data[$post_data_str]");
    
    $this->form_validation->run();
    

    然后,只需根据您需要验证的内容编写自定义验证函数。

    function _validate_project_data($value, $request)
    {
        // A callback rule check is being attempted by the CI validator 
        // $value is the actual value of the submission, while $request is the key and value
    
        $request = explode(",", $request);
        $request = str_replace("DELIMITEDCOMMA", ",", $request);
    
        // rename the keys in the request back to the original convention
    
        parse_str($request[0], $request); 
        //var_dump($request);
    
        // perform validation here and return true or false (valid or invalid)      
    
    }
    

    【讨论】:

    • 我离开了一段时间,我不明白你的意思。目前我正在遍历所有字段并返回一个错误,即使一个错误失败。不是很方便。但我会尝试理解您的意思并尝试实施。
    【解决方案3】:

    不完全确定您的意思,因为无论您采用哪种方式,都必须单独检查这些字段。除非你连接所有输入并检查它?也许我错过了那里的一些东西。

    去客户端吧:http://flowplayer.org/tools/demos/validator/index.html

    服务器端:http://formigniter.org/

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 2016-07-22
      • 2017-06-27
      • 2019-07-12
      相关资源
      最近更新 更多