【问题标题】:CodeIgniter 3 - Callable Form Validation by Config file not workingCodeIgniter 3 - 配置文件的可调用表单验证不起作用
【发布时间】:2015-06-01 23:56:22
【问题描述】:

validation rules are placed in a separate config file 时,我无法让 CodeIgniter 3 的callable form validation feature 工作。

我收到以下错误消息:

遇到 PHP 错误
严重性:通知
消息:未定义的属性:CI_Config::$form_validation_callback_library

带有表单验证规则的配置文件如下(config/fvalidation.php):

$config['client_details'] = array(
    array(
            'field' => 'client_abn',
            'label' => 'Client ABN',
            'rules' => array('trim', 'required', array('abn_callable', array($this->form_validation_callback_library, 'abn_check'))),
            'errors' => array('abn_callable' => 'Invalid ABN has been entered %s.')
    )

);

试图调用的表单验证类是(即 $this->form_validation_callback_library):

class Form_validation_callback_library
{

    public function abn_check()
    {

        $this->load->library('abn_validator');

        $abn = $this->input->post_get('abn', TRUE);

        if (!$this->abn_validator->isValidAbn($abn)) {
            return FALSE;
        }

        return TRUE;

    }


}

控制器是:

        $this->config->load('fvalidation');
        $validation_rules = $this->config->item('client_details');
        $this->form_validation->set_rules($validation_rules);               

        if ($this->form_validation->run() == FALSE) {
            // show form
        } else {
            // process form data
        }

任何帮助将不胜感激。

干杯, VeeDee

【问题讨论】:

  • 我认为 CodeIgniter3 不支持此功能,因此在下面创建了一个解决方法:stackoverflow.com/questions/30585229/… 任何有关改进或实现此目的的更好方法的建议将不胜感激

标签: php forms codeigniter validation codeigniter-3


【解决方案1】:

我会在回调下面使用 codeigniter 回调示例

http://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

<?php

class Example extends CI_Controller {

public function index() {
    $this->load->library('form_validation'); 

    $this->form_validation->set_rules('client_abn', 'ABN Number', 'required|callback_checkabn');

    if ($this->form_validation->run() == FALSE) {

        $this->load->view('something');

    } else {

        // Redirect to success page i.e login or dashboard or what ever

        redirect('/'); // Currently would redirect to home '/'

    }
}

public function checkabn() {

    $this->load->library('abn_validator');

    $abn = $this->input->post('abn');

    if (!$this->abn_validator->isValidAbn($abn)) {
        $this->form_validation->set_message('checkabn', 'Invalid ABN has been entered %s.');
        return FALSE;
    } else {
        return TRUE;
    }

}

}

并在您的视图中或上方的表单中添加

<?php echo validation_errors('<div class="error">', '</div>'); ?>

<form action="<?php echo base_url('example');?>" method="post">
    <input type="text" name="client_abn" placeholder="" value="" />
</form>

【讨论】:

  • 感谢@wolfgang1983。这是一个很好的解决方案,但对于我正在开发的应用程序,最好将验证规则/函数分开,因为多个控制器正在重复使用验证函数(例如 abn_check())。
【解决方案2】:

这是我们在 CI 中运行自定义表单验证时最常见的问题。无论回调函数是在同一个控制器中还是在回调函数库中,我们都需要传递包含回调函数的类的可访问对象。 所以当你运行

$callable_validations = new Form_validation_callback_library();

$this->form_validation->run($callable_validations)

【讨论】:

    【解决方案3】:

    目前看来这在 CodeIgniter 3 上是不可能的。

    我已经创建了一个粗略的解决方法.. 所以请继续改进它,因为它看起来不漂亮:)

    像这样更新配置文件(/config/fvalidation.php):

    $config['client_details'] =  = array(
            array(
                    'field' => 'client_abn',
                    'label' => 'Client ABN',
                    'rules' => array('trim', 'required', array('abn_callable', array("library:form_validation_callback_library", 'abn_check'))),
                    'errors' => array('abn_callable' => 'Invalid %s has been entered .')
            )
    );
    

    请注意上面配置文件中的以下行,因为我们将在控制器代码中将它们用作标志:

    array('abn_callable', array("library:form_validation_callback_library", 'abn_check'))
    

    除了我们加载实例(/libraries/Form_validation_callback_library.php)之外,库几乎相同:

    class Form_validation_callback_library
    {
        private $_CI;
    
        function Form_validation_callback_library() {
            $this->_CI =& get_instance();
    
            log_message('info', "Form_validation_callback_library Library Initialized");
        }
    
        public function abn_check($abn)
        {
    
            $this->_CI->load->library('abn_validator');
    
    
            if (!$this->_CI->abn_validator->isValidAbn($abn)) {
                return FALSE;
            }
    
            return TRUE;    
        }
    
    }
    

    在控制器中我们加载库(/controllers/Foo.php):

    // load the config file and store
    $this->config->load('fvalidation', TRUE);
    $rule_dataset = $this->config->item('client_details', 'fvalidation');
    
    // search and load the 'callable' library
    foreach ($rule_dataset as $i => $rules) {
        if (isset($rules['rules'])) {
            foreach ($rules['rules'] as $k => $rule) {
                if (is_array($rule) && preg_match("/_callable/",$rule[0]) && isset($rule[1][0])) {                      
                    list ($load_type, $load_name) = explode(":", $rule[1][0]);                      
                    // load the library
                    $this->load->$load_type($load_name);                        
                    $rule_dataset[$i]['rules'][$k][1][0] = $this->$load_name;
    
                }
            }
        }           
    }
    
    // set the rules
    $this->form_validation->set_rules($rule_dataset);
    
    // load the form
    if ($this->form_validation->run() == FALSE) {
      // show form
    } else {
        // process form data
    }
    

    【讨论】:

      【解决方案4】:

      我做了一些类似于 Vidura 的事情,但通过添加 MY_Form_validation.php 和以下代码来扩展表单验证库

      <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
      class GS_Form_validation extends CI_Form_validation {
      
          public function set_rules($field, $label = '', $rules = array(), $errors = array())
          {
              if (is_array($rules))
              {
                  foreach ($rules as &$rule)
                  {
                      if (is_array($rule))
                      {
                          if (is_array($rule[1]) and is_string($rule[1][0]))
                          {
                              // handles rule like ['password_check', ['library:passwords', 'check_valid_password']]
                              // You would set_message like $this->form_validation->set_message('password_check', 'Incorrect password');
                              // The advantage of defining the rule like this is you can override the callback functions error message
                              list ($load_type, $load_name) = explode(":", $rule[1][0]);
                              $CI =& get_instance();
                              $CI->load->$load_type($load_name);
                              $rule[1][0] = $CI->$load_name;
                          }
                          else if (is_string($rule[0]))
                          {
                              // handles rule like ['library:password', 'check_valid_password']
                              // You would set_message like $this->form_validation->set_message('check_valid_password', 'Incorrect password');
                              list ($load_type, $load_name) = explode(":", $rule[0]);
                              $CI =& get_instance();
                              $CI->load->$load_type($load_name);
                              $rule[0] = $rule[1];
                              $rule[1] = [$CI->$load_name, $rule[1]];
                          }
                      }
                  }
              }
      
              return parent::set_rules($field, $label, $rules, $errors);
          }
      }
      

      然后你可以定义回调到库函数,例如:

      $this->form_validation->set_rules(['library:passwords', 'check_valid_password']);
      

      其中密码是库,check_valid_password 是方法。

      【讨论】:

        【解决方案5】:

        我只是做了(config/form_validation.php):

        $CI =& get_instance();
        $CI->load->model('form_validation_callback_library');
        
        $config['client_details'] = array(
            array(
                    'field' => 'client_abn',
                    'label' => 'Client ABN',
                    'rules' => array('trim', 'required', array('abn_callable', array($CI->form_validation_callback_library, 'abn_check'))),
                    'errors' => array('abn_callable' => 'Invalid ABN has been entered %s.')
            )
        

        它对我有用...

        我在 Codeigniter 3.0.4 上运行

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-29
          • 1970-01-01
          • 2012-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多