【发布时间】:2009-09-10 04:22:14
【问题描述】:
在 CakePHP 中,是否有一种内置方法可以验证日期是否在特定范围内?例如,检查某个日期是否在将来?
如果唯一的选择是编写我自己的自定义验证函数,因为它对我的所有控制器都非常通用且有用,那么将其放入哪个文件最好?
【问题讨论】:
标签: php validation cakephp
在 CakePHP 中,是否有一种内置方法可以验证日期是否在特定范围内?例如,检查某个日期是否在将来?
如果唯一的选择是编写我自己的自定义验证函数,因为它对我的所有控制器都非常通用且有用,那么将其放入哪个文件最好?
【问题讨论】:
标签: php validation cakephp
我刚刚使用 Cake 2.x 想出了一个很好的简单解决方案,请务必将以下内容放在您的模型类上方:
App::uses('CakeTime', 'Utility');
使用如下验证规则:
public $validate = array(
'deadline' => array(
'date' => array(
'rule' => array('date', 'ymd'),
'message' => 'You must provide a deadline in YYYY-MM-DD format.',
'allowEmpty' => true
),
'future' => array(
'rule' => array('checkFutureDate'),
'message' => 'The deadline must be not be in the past'
)
)
);
最后是自定义验证规则:
/**
* checkFutureDate
* Custom Validation Rule: Ensures a selected date is either the
* present day or in the future.
*
* @param array $check Contains the value passed from the view to be validated
* @return bool False if in the past, True otherwise
*/
public function checkFutureDate($check) {
$value = array_values($check);
return CakeTime::fromString($value['0']) >= CakeTime::fromString(date('Y-m-d'));
}
【讨论】:
在 Google 上快速搜索“CakePHP 未来日期验证”会为您提供以下页面:http://bakery.cakephp.org/articles/view/more-improved-advanced-validation(对“未来”进行页面搜索)
此代码(来自链接)应该可以满足您的需要
function validateFutureDate($fieldName, $params)
{
if ($result = $this->validateDate($fieldName, $params))
{
return $result;
}
$date = strtotime($this->data[$this->name][$fieldName]);
return $this->_evaluate($date > time(), "is not set in a future date", $fieldName, $params);
}
【讨论】:
在您的 appmodel
中添加以下功能 /**
* date range validation
* @param array $check Contains the value passed from the view to be validated
* @param array $range Contatins an array with two parameters(optional) min and max
* @return bool False if in the past, True otherwise
*/
public function dateRange($check, $range) {
$strtotime_of_check = strtotime(reset($check));
if($range['min']){
$strtotime_of_min = strtotime($range['min']);
if($strtotime_of_min > $strtotime_of_check) {
return false;
}
}
if($range['max']){
$strtotime_of_max = strtotime($range['max']);
if($strtotime_of_max < $strtotime_of_check) {
return false;
}
}
return true;
}
用法
'date' => array(
'not in future' => array(
'rule' =>array('dateRange', array('max'=>'today')),
)
),
【讨论】: