[eluser]CI Evan[/eluser]
Seems the form validation class won't execute any callbacks or formatting functions unless the field is required.
Code:
// controller
function save()
{
$rules = array(
array(
'field' => 'effective',
'label' => 'Effective Date',
'rules' => 'trim|required|callback__valid_date|to_timestamp'
),
array(
'field' => 'expiration',
'label' => 'Expiration Date',
'rules' => 'trim|callback__valid_date_or_blank|to_timestamp'
)
);
// to_timestamp($str) is defined in an autoloaded helper
$this->form_validation->set_rules($rules);
$this->form_validation->set_message('_valid_date', 'The %s field is invalid. Use MM/DD/YYYY.');
$this->form_validation->set_message('_valid_date_or_blank', 'The %s field is invalid. Use MM/DD/YYYY.');
$action = ($this->input->post('id') == 0) ? 'create' : 'edit';
if($this->form_validation->run())
{
print_r($_POST);
}
else
{
echo 'failed';
}
}
function _valid_date($date){ return is_valid_date($date); }
function _valid_date_or_blank($date){ return (strlen($date) > 0) ? is_valid_date($date) : TRUE; }
// autoloaded helper
function to_timestamp($date)
{
if(!(strlen($date) > 0)) return $date;
$pieces = explode('/', $date);
$human = sprintf('%3$s-%1$s-%2$s 0:0:0 AM', $pieces[0], $pieces[1], $pieces[2]);
return human_to_unix($human);
}
function is_valid_date($date)
{
// format check
$reg_ex = "@(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\d{2}@";
if((preg_match($reg_ex, $date) != 1) OR (strlen($date) != 10)) return FALSE;
$pieces = explode('/', $date);
// semantic check (do not allow 02/31/2009)
if(!checkdate($pieces[0], $pieces[1], $pieces[2])) return FALSE;
return TRUE;
}
With valid input for both fields, $_POST['effective'] is processed and outputted as a numeric timestamp, where as $_POST['expiration'] is not processed at all and instead outputted as the string originally entered (12/31/2009).
What am I doing wrong?