我正在使用Codeigniter并有两个名为event_start_time
和event_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 :(得分:0)
嗨CI中没有这样的选项。
你必须简单地使用比较运算符,如下所示:
if($event_start_time > $event_end_time){
/.../
}
答案 1 :(得分:0)
有几种方法可以解决这个问题,但这是我要尝试的第一件事(代码未经测试)。
假设这是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)在您的控制器,模型或您正在验证帖子的任何地方,加载并应用验证规则,而不是指定它们的执行方式。
$this->config->load('validation/validate');
$this->form_validation->set_rules( config_item('validation_rules') );