Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date validation rules in yii

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

like image 859
klark Avatar asked Mar 07 '14 08:03

klark


2 Answers

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.

like image 60
JamesG Avatar answered Sep 24 '22 15:09

JamesG


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;
     }
like image 41
Rishabh Avatar answered Sep 21 '22 15:09

Rishabh