Extending form validation in Codeigniter

后端 未结 3 990
故里飘歌
故里飘歌 2020-12-10 16:01

I have placed this class file called \'My_Form_validation.php\' into \'application/core\' and I have also tried placing it in \'application/libraries\'.

In my contro

相关标签:
3条回答
  • 2020-12-10 16:32

    I know this is old, but just in case someone else stumbles on this in the modern day like I did, here's a quick example. (Currently using 3.0.6, but I believe this will work on 2 as well.)

    class MY_Form_validation extends CI_Form_validation { // Capitalization matters
    
      protected $CI;
    
      public function __construct() {
          parent::__construct();
      }
    
      /**
       * Valid Date
       *
       * Verify that the date value provided can be converted to a valid unix timestamp
       *
       * @param string  $str
       * @return    bool
       */
    
      public function valid_date($str) {
          $CI = $this->CI =& get_instance(); // Get your CodeIgniter instance
    
          if (($str = strtotime($str)) === FALSE) { // Basic timestamp check
              // Set error message by calling the method through the CI instance.
              // Obviously must be done BEFORE returning any value
              $this->CI->form_validation->set_message('valid_date', '{field} must be a valid date.');
              return FALSE;
          }
    
          return TRUE;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 16:42

    Because you're extending a CodeIgniter library and not a core component, you want to place that in application/libraries (not application/core).

    And of course, don't forget to load the Form_validation library within your controller code.

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

    Other things to check:

    • Filename case sensitivity (MY_Form_validation.php loads while My_Form_validation.php won't)
    • Class name case sensitivity (class MY_Form_validation extends CI_Form_validation)

    Reference material:

    • Extending Core Classes
    • Extending Native Libraries
    0 讨论(0)
  • 2020-12-10 16:47

    You have to add $rules on your __construct method and also pass this to parent constructor

    eg:

    function __construct($rules = array())
    {
        parent::__construct($rules);
    }
    

    Look at Form_validation and provide same variables.

    0 讨论(0)
提交回复
热议问题