有谁知道如何在 php 的 codeigniter 中使用回调函数验证日期。我试图使from_date大于to_date。我已经转换为对象并比较日期。
我尝试使用表单验证和回调,但它没有返回 true。 我错在哪里?提前谢谢.. 我的代码如下。.
public function save()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('from_date', 'trim|required');
$this->form_validation->set_rules('to_date','trim|required|callback_checkdate');
}
我的回调函数是
public function checkdate()
{
if($this->input->post('from_date')!='' && $this->input->post('to_date')!='' && DateToDateObject($this->input->post('from_date')) <= DateToDateObject($this->input->post('to_date')))
{
return FALSE;
}
else
{
return TRUE;
}
}
您的回调代码应包含我的答案中提到的set_message
方法。此外,您无需检查($this->input->post('from_date')!='' && $this->input->post('to_date')!='')
,因为 set_rules
中已经需要这些。
public function checkdate()
{
$from_date= new DateTime($this->input->post('from_date'));//date-formate :- YYYY-MM-DD
$to_date= new DateTime($this->input->post('to_date'));
if( $from_date >= $to_date)//To date must be higher i think
{
$this->form_validation->set_message('checkdate', 'From date is bigger then to date.');
return FALSE;
}
else
{
return TRUE;
}
}
对于 ajax 您的控制器代码应该是这样的
public function save()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('from_date', 'trim|required');
$this->form_validation->set_rules('to_date','trim|required|callback_checkdate');
if ($this->form_validation->run() == FALSE)
{
$errors = array();
foreach ($this->input->post() as $key => $value)
{
$errors[$key] = form_error($key);
}
$response['errors'] = array_filter($errors); // Some might be empty
$response['status'] = FALSE;
}
else
{
$response['status'] = TRUE;
}
header('Content-type: application/json');
echo json_encode($response);
exit;
}
在您的 ajax 请求中使用 datatype:'json'
并在 ajax success
函数使用中显示错误
success:function(data)
{
if (data.status == true)
{
console.log("form has no error");
}
else
{
console.log("form has error");
$.each(data.errors, function(key, val) {
$('[name="'+ key +'"]', form).after(val);
})
}
}