我的模型驗證輸入日期時,轉換格式類型並導致麻煩。驗證日期格式的模型
<?php $form = yii\widgets\ActiveForm::begin([
'options' => ['class' => ''],
'fieldConfig' => ['template' => "{label}\n{input}\n{hint}\n{error}"]
]); ?>
<div class="col-md-4">
<?= $form->field($model, 'startDate')->widget(DatePicker::classname(),
[
'language' => 'pt-BR',
'dateFormat' => 'dd/MM/yyyy',
'clientOptions' => [
'yearRange' => '2005:+0',
'defaultDate' => date('d/m/Y', strtotime('-7days'))
],
'options' => [
'class' => 'form-control',
'maxlength' => '10',
'placeholder' => 'Data inicial',
]
]
)->label(false) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'endDate')->widget(DatePicker::classname(),
[
'language' => 'pt-BR',
'dateFormat' => 'dd/MM/yyyy',
'clientOptions' => [
'yearRange' => '2005:+0',
'defaultDate' => date('d/m/Y')
],
'options' => [
'class' => 'form-control',
'maxlength' => '10',
'placeholder' => 'Data final',
]
]
)->label(false) ?>
</div>
<div class="col-md-4">
<?= Html::submitButton('Filtrar', ['class' => 'btn btn-primary']) ?>
<?php yii\widgets\ActiveForm::end(); ?>
</div>
及型號:
<?php
namespace frontend\models;
use yii\base\Model;
use Yii;
class Analysis extends Model
{
public $startDate;
public $endDate;
public function rules()
{
return [
['startDate', 'required'],
['startDate', 'date', 'format' => 'dd/MM/yyyy'],
['startDate', 'checkDateToday'],
['startDate', 'checkGAMinDate'],
['endDate', 'required'],
['endDate', 'date', 'format' => 'dd/MM/yyyy'],
['endDate', 'checkDateToday'],
['endDate', 'checkGAMinDate'],
['endDate', 'checkDateGreaterThan']
];
}
public function checkDateToday($attribute, $params)
{
if($this->$attribute <= date('d/m/Y')){
return true;
} else {
var_dump($this->$attribute);
$this->addError($attribute, $attribute . ' não pode ser maior que hoje: ' . date('d/m/Y'));
}
}
public function checkGAMinDate($attribute, $params)
{
if($this->$attribute > date('01/01/2005')){
return true;
} else {
$this->addError($attribute, $attribute . ' não pode ser menor que 01/01/2005');
}
}
public function checkDateGreaterThan($attribute, $params)
{
if($this->endDate < $this->startDate){
return true;
} else {
$this->addError($attribute, 'Data final não pode ser maior que data incial.');
}
}
public function attributeLabels()
{
return [
'startDate' => Yii::t('app', 'Data inicial'),
'endDate' => Yii::t('app', 'Data final'),
];
}
}
當我把像 「25/12/2015」( 'd/M/Y'),驗證後的模型迴歸的日期:「12/25/2015" 年。發生什麼事了?
奇怪,我想,但我不能複製這個錯誤。在您的數據庫中,日期的格式與表單(日/月/年)相同?如果沒有,那是,你能展示如何在控制器中保存這個屬性? – Clyff
我不保存這些屬性,只在模型中驗證。我將這些日期傳遞給控制器以用於api調用。 '$ model-> load(Yii :: $ app-> request-> post())&& $ model-> validate()' –