CakePHP验证日期

nic*_*ckf 3 php validation cakephp

在CakePHP中,是否有内置的方法来验证日期在一定范围内?例如,检查某个日期是否在将来?

如果唯一的选择是编写我自己的自定义验证函数,因为它对我的所有控制器都非常通用且有用,这是最好的文件吗?

Hel*_*man 6

我刚刚使用Cake 2.x想出了一个很容易解决这个问题的方法,请确保在模型类上面放置以下内容:

App::uses('CakeTime', 'Utility');
Run Code Online (Sandbox Code Playgroud)

使用如下的验证规则:

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'
        )
    )
);
Run Code Online (Sandbox Code Playgroud)

最后是自定义验证规则:

/**
 * 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'));
}
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用CakeTime :: isFuture来简化一些事情.这是在v2.4中添加的 (3认同)