CodeIgniter: Validate datetime field

2019-09-16 14:12发布

问题:

I tried This code, but the error is not display.

$this->form_validation
     ->set_rules('fromdatetime',
                 'fromdatetime',
                 '|required|valid_date[m/d/y,/]');

How can I validate the datetime format using codeigniter set rules.

回答1:

You can use this extended library:

https://github.com/lumoz/codeigniter-form-validation



回答2:

You may use something like this (dd/mm/yyyy):

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

Change the regular expression if you want to use a different format. You may also use a custom callback function like this:

public function checkDateTime($dt)
{
    $pattern = 'same regex pattern';
    if(preg_match($pattern, $this->input->post('fromdatetime'))) {
        return true;
    }
    else {
        $this->form_validation->set_message('checkDateTime', 'Invalid Date!');
        return false;
    }
}

Set the rule as:

this->form_validation
    ->set_rules('fromdatetime', 'Date','required|callback_checkDateTime');