codeigniter 验证开始时间大于结束时间

sqyvllje  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(238)

我使用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');
cygmwpex

cygmwpex1#

Hi CI中没有此选项。
您必须简单地使用比较运算符,如下所示:
if($event_start_time > $event_end_time){ /.../ }

llmtgqce

llmtgqce2#

有几种方法可以实现这一点,但这是我首先要尝试的(代码未经测试)。
假设这是CodeIgniter 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)在/application/models/validation/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)在您的控制器、模型或任何您要验证post的地方,加载并应用验证规则,而不是指定它们是如何进行的。

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

相关问题