Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Framework 2.0 Rules Date Validator

I am using Yii Framework 2.0. I have a form with a text input field which is meant for a date. I have read the Yii Framework 2.0 about the Class yii\validators\Validator and known all the validator keys which can be used inside of the rules() method in a model class. When I use the date key as below, it does not validate anything. It means that I still can put some text in that input field and can post the form.

When I changed it into boolean or email, I could see that it validates very well when I put something wrong in the input field. How can I validate a date value inside of an input field with Yii Framework 2.0?

My rules() method:

public function rules()
{
    return [
         [['inputfield_date'], 'required'],
         [['inputfield_date'], 'safe'],
         [['inputfield_date'], 'date'],
    ];
}

My view page:

<?php $form = ActiveForm::begin(); ?>
     <?= $form->field($model, 'inputfield_date')->textInput(); ?>
<?php ActiveForm::end(); ?>
like image 683
O Connor Avatar asked Sep 28 '14 18:09

O Connor


3 Answers

Boy the Yii docs suck. They don't even give an example. Working from O'Connor's answer, this worked for me since I was assigning the value in 2015-09-11 format.

// Rule
[['event_date'], 'date', 'format' => 'php:Y-m-d']
// Assignment
$agkn->event_date = date('Y-m-d');

The docs don't even specify where format or timestampAttribute came from, or how to use them. It doesn't even say what the heck from_date and to_date are. And most of all, no examples!

like image 189
Chloe Avatar answered Nov 14 '22 14:11

Chloe


Working solution. My rules() method:

public function rules()
{
   return [
     [['inputfield_date'], 'required'],
     [['inputfield_date'], 'safe'],
     ['inputfield_date', 'date', 'format' => 'yyyy-M-d H:m:s'],
   ];
}

My form in the view page:

<?php $form = ActiveForm::begin(); ?>
   <?= $form->field($model, 'inputfield_date')->textInput(); ?>
<?php ActiveForm::end(); ?>

My method in controller:

if ($model->load(Yii::$app->request->post()) && $model->validate()):
        if($model->save()):
            // some other code here.....
        endif;
endif;

Note that the date format depends on how you define your date format input field. Note once again that this is not an AJAX validator. After clicking on the submit button, you will see the error message if you enter something else which is not a date.

like image 10
O Connor Avatar answered Nov 14 '22 13:11

O Connor


You can validate for date like this from model rules

public function rules(){
    return [
        [['date_var'],'date', 'format'=>'d-m-yy'],
        [['from_date', 'to_date'], 'default', 'value' => null],
        [['from_date', 'to_date'], 'date'],
    ];
}
like image 3
Azraar Azward Avatar answered Nov 14 '22 13:11

Azraar Azward