2017-08-12 63 views
0

我正在使用Codeigniter,并有两个变量,分别称为event_start_timeevent_end_time。我需要检查开始时间是否大于结束时间。确认开始时间大于结束时间

我该如何使用Codeigniter中的表单验证库来验证它?

$this->form_validation->set_rules('event_start_time', 'Starttid', 'required|strip_tags|trim'); 
$this->form_validation->set_rules('event_end_time', 'Sluttid', 'required|strip_tags|trim'); 

回答

0

嗨CI中没有这样的选项。

你要简单的使用操作比较象下面这样:

if($event_start_time > $event_end_time){ /.../ }

0

有,你可以处理这个几个方法,但是这是我想尝试(未测试的代码)的第一件事。

假设这是笨3

1)在/application/config/validation/validate.php

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

// CI not normally available in config files, 
// but we need it to load and use the model 
$CI =& get_instance(); 

// Load the external model for validation of dates. 
// You will create a model at /application/models/validation/time_logic.php 
$CI->load->model('validation/time_logic'); 

$config['validation_rules'] = [ 
    [ 
     'field' => 'event_start_time', 
     'label' => 'Starttid', 
     'rules' => 'trim|required|strip_tags' 
    ], 
    [ 
     'field' => 'event_end_time', 
     'label' => 'Sluttid', 
     'rules' => [ 
      'trim', 
      'required', 
      'strip_tags' 
      [ 
       '_ensure_start_time_end_time_logic', 
       function($str) use ($CI) { 
        return $CI->time_logic->_ensure_start_time_end_time_logic($str); 
       } 
      ] 
     ] 
    ] 
]; 

2创建以下配置文件中)在创建验证模型/应用/模型/验证/ time_logic.php

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class Time_logic extends CI_Model { 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function _ensure_start_time_end_time_logic($str) 
    { 
     // Making an assumption that your posted dates are a format that can be read by DateTime 
     $startTime = new DateTime($this->input->post('event_start_time')); 
     $endTime = new DateTime($str); 

     // Start time must be before end time 
     if($startTime >= $endTime) 
     { 
      $this->form_validation->set_message(
       '_ensure_start_time_end_time_logic', 
       'Start time must occur before end time' 
      ); 
      return FALSE; 
     } 

     return $str; 
    } 

} 

3)在你的控制器,型号,或者是任何一个是你要验证后,加载和应用验证规则,而不是规范让他们知道你是如何做到的。

$this->config->load('validation/validate'); 
$this->form_validation->set_rules(config_item('validation_rules')); 
相关问题