在CakePHP中,是否有内置的方法来验证日期在一定范围内?例如,检查某个日期是否在将来?
如果唯一的选择是编写我自己的自定义验证功能,因为它对我的所有控制器都非常通用且有用,这是最好的文件吗?
答案 0 :(得分:6)
我刚刚使用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'));
}
答案 1 :(得分:3)
答案 2 :(得分:3)
快速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);
}
答案 3 :(得分:1)
在 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')),
)
),