2009-09-10 77 views
1

在CakePHP中,有沒有驗證的日期是在一定範圍內的一個內置的方式嗎?例如,檢查某個日期是否在未來?CakePHP的驗證的日期

如果唯一的選擇就是寫我自己的自定義驗證功能,因爲這將是非常普通的和有用的我所有的控制器,這是把它放在最佳的文件?

回答

1

AFAIK有日期範圍沒有內置的驗證。最接近它的將是range,但前提是您希望所有日期都是UNIX時間戳。

你可以把自己的驗證方法在AppModel,它會在所有型號。

3

快速谷歌搜索「CakePHP的未來日期驗證」給你這個頁面:http://bakery.cakephp.org/articles/view/more-improved-advanced-validation(對於「未來」做一個頁面搜索)

此代碼(來自鏈接)應該做你需要什麼

App::uses('CakeTime', 'Utility'); 

使用validat:

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); 
    } 
+0

我錯過了什麼? ;) – 2009-09-10 06:05:03

+0

適當的Markdown代碼格式。 :) – deceze 2009-09-11 02:44:30

4

我只是用蛋糕2.x中,請務必將您的模型類和以下的想出了一個漂亮的簡單的解決這個問題離子規則如下所示:

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

如果你想成爲更加靈活和檢查對另一場(如果你發佈兩個日期例如,想一個是前一後) - 嘗試validateDate()等從這裏:https://github.com/dereuromark /tools/blob/master/Model/MyModel.php#L1191 – mark 2013-03-05 14:56:09

+0

很好的建議,我可能必須使用在未來的需求總是在不斷變化看來,偉大的工作。 – HelloSpeakman 2013-04-24 12:51:26

+2

你也可以使用CakeTime :: isFuture來簡化一些事情。這是在v2.4中添加的 – 2014-07-28 12:38:10

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')), 
     ) 
    ),