validação CakePHP para datas
-
05-07-2019 - |
Pergunta
Em CakePHP, há um built-in maneira de validar uma data para estar dentro de um determinado intervalo? Por exemplo, verifique se uma determinada data é no futuro?
Se a única opção é escrever minha própria função de validação personalizada, uma vez que vai ser muito genérico e útil a todos os meus controladores, que é o melhor arquivo para colocá-lo?
Outras dicas
Eu só veio com uma agradável fácil correção para esse problema usando 2.x bolo, com certeza ser para colocar o seguinte acima de sua classe de modelo:
App::uses('CakeTime', 'Utility');
Use uma regra de validação como o seguinte:
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'
)
)
);
Finalmente, a regra de validação personalizada:
/**
* 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'));
}
Uma rápida pesquisa do Google para "validação data futura CakePHP" dá-lhe esta página: http://bakery.cakephp.org/articles/view/more-improved-advanced-validation (fazer uma pesquisa página para "futuro")
Este código (a partir do link) deve fazer o que você precisa
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);
}
Adicione o abaixo função em seu 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;
}
Uso
'date' => array(
'not in future' => array(
'rule' =>array('dateRange', array('max'=>'today')),
)
),