Creating a custom callback validation rule in codeigniter 2.x

How can I create my own validation rule in codeigniter 2.x, which can be widely used throughout the application?

I know that we can create callback functions in the controller, which can then be used in the validation rule as -

$this->form_validation->set_rules('user_dob', 'Date of Birth', 'required|callback_validDate|callback_validAge');

And now we can create a check function in the controller as -

public function validDate($date) {
     $d = DateTime::createFromFormat('d-M-Y', $date);
     if ($d && $d->format('d-M-Y') == $date)
          return TRUE;

     $this->form_validation->set_message('validDate', ' %s is not in correct date format');
     return FALSE;
}

But there is a limitation. I can use this method only inside this particular controller. This function cannot be used for other controllers. I will have to write the same code again.

To do this, I tried to create an auxiliary file with this check function, but again, no luck.

So, how can I reuse the validation function created once in a common file in codeigniter?

+4
1

. , .

MY_Form_validation.php /application/libraries/ -

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

    protected $CI;

    function __construct() {
        parent::__construct();
        $this->CI = & get_instance();
    }

    function validDate($date) {
        $this->CI->form_validation->set_message('validDate', ' %s is not in correct date format');

        $d = DateTime::createFromFormat('d-M-Y', $date);
        if ($d && $d->format('d-M-Y') == $date)
            return TRUE;

        return FALSE;
    }
}

-

$this->form_validation->set_rules('user_dob', 'Date of Birth', 'required|validDate|validAge');

-

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

- https://arjunphp.com/custom-validation-rules-codeigniter/

+1

Source: https://habr.com/ru/post/1655968/


All Articles