首页 文章

使用codeigniter中的回调函数验证日期

提问于
浏览
1

有没有人知道如何使用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;
         }
     }

1 回答

  • 2

    您的回调代码应该包含我的答案中提到的 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);
            })
        }
    }
    

相关问题