3

I am using PHP CodeIgniter. I have kept validation in a function. I do not know the validation rule for date and time calendar in CodeIgniter. Can anyone give me an idea?

My code is :

$this->ref_valid_rules = array( 
                        array('field' => 'meeting_heading',
                              'label' => 'meeting heading',
                              'rules' => 'trim|required'), 
                        array('field' => 'meeting_agenda',
                              'label' => 'meeting agenda',
                              'rules' => 'trim|required'),
                        array('field' => 'venue',
                              'label' => 'venue',
                              'rules' => 'trim|required'),
                        array('field' => 'date',
                              'label' => 'date time',
                              'rules' => 'required') );
Brian
  • 14,610
  • 7
  • 35
  • 43
Deepak Keynes
  • 311
  • 2
  • 16

2 Answers2

1

You can try

$this->form_validation->set_rules('date', 'date time', 'regex_match[(0[1-9]|1[0-9]|2[0-9]|3(0|1))-(0[1-9]|1[0-2])-\d{4}]');

http://www.formget.com/codeigniter-form-validation-date/

and other answers Codeigniter - Date format - Form Validation

Date validation in codeigniter

or you can try the set validation rules using callbacks

  function regex_date($date) {

    $data =  preg_match('@^Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec-[0-9]{2}-[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}$@', $date);

    return $data;
}

the function will return true or false

Community
  • 1
  • 1
Oli Soproni B.
  • 2,774
  • 3
  • 22
  • 47
0

You can create your own callback function for validating the date.

Example below is for validating dd/mm/yyyy format so you can modify it as it fits your requirement. This is to give you hint about callbacks.

Pay attention to callback_validate_date in set_rules(). That's your callback function. It calles validate_date() behind the scene.

$this->form_validation->set_rules('date_field', 'Date', 'trim|exact_length[10]|callback_validate_date|xss_clean');

Callback

public function validate_date($date)
{
    //Some date fields are not compulsory
    //If all of them are compulsory then just remove this check
    if ($date == '')
    {
        return true;
    }

    //If in dd/mm/yyyy format
    if (preg_match("^\d{2}/\d{2}/\d{4}^", $date))
    {
        //Extract date parts
        $date_array = explode('/', $date);

        //If it is not a date
        if (! checkdate($date_array[1], $date_array[0], $date_array[2]))
        {
            $this->form_validation->set_message('validate_date', 'The %s field must contain a valid date.');
            return false;
        }
    }
    //If not in dd/mm/yyyy format
    else
    {
        $this->form_validation->set_message('validate_date', 'The %s field must contain a valid date.');
        return false;
    }

    return true;
}
BentCoder
  • 12,257
  • 22
  • 93
  • 165