I have a problem with validating rules for dates, when I enter invalid date like 'xxxx', I dont get the validator running, but it runs for other fields with required validator.
the form
?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'enableAjaxValidation'=>false,
'enableClientValidation'=>true,
)); ?>
....
<div class="row">
<?php echo $form->labelEx($model,'fromDate'); ?>
<?php echo $form->textField($model,'fromDate'); ?>
<?php echo $form->error($model,'fromDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'toDate'); ?>
<?php echo $form->textField($model,'toDate'); ?>
<?php echo $form->error($model,'toDate'); ?>
</div>
the rules in the post model
public function rules()
{
return array(
array('fromDate, toDate', 'date', 'format'=>'dd-mm-yyyy H:m:s', 'allowEmpty'=>false),
array('subject', 'required'),
);
...
}
Thank you in advance for your help
I don't find Yii's CDateValidator particularly flexible, and I usually go down the route of creating a custom validation rule:
Add this to your Model:
public function isValidDate($attribute, $params)
{
if(!strtotime($this->$attribute))
{
$this->addError($attribute, $attribute . ' was not a valid date');
}
}
Then assign the custom validator to your attribute in the rules() array:
array('fromDate, toDate', 'isValidDate'),
You could expand on that to make sure the dates are within a reasonable time frame, and that the toDate
is after fromDate
etc.
You can use Yii widget
<div class="row">
<?php
echo $form->labelEx($model, 'fromDate');
$this->widget('CJuiDateTimePicker', array(
'model' => $model, //Model object
'attribute' => 'fromDate', //attribute name
'mode' => 'date', //use "time","date" or "datetime" (default)
'options' => array(
'dateFormat' => "dd/mm/yy",
'defaultDate' => "new Date()",
), // jquery plugin options
'htmlOptions' => array(
'id' => 'fromDate',
),
));
?>
</div>
and in action :
if ($model->fromDate != '') {
$temp = strtotime(str_replace('/', '-', $model->fromDate));
$temp = date('Y-m-d', $temp);
$model->fromDate = $temp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With