Yii Framework 2.0 Rules Date Validator

后端 未结 5 2157
情书的邮戳
情书的邮戳 2021-02-19 03:50

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\\Validat

相关标签:
5条回答
  • 2021-02-19 04:22

    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'],
        ];
    }
    
    0 讨论(0)
  • 2021-02-19 04:24

    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.

    0 讨论(0)
  • 2021-02-19 04:29

    Firstly, date validation relies on $model->validate(), so does not work inline but is only triggered by clicking Save (i.e. it's typically applied in actionCreate/actionUpdate).

    Secondly, it's applied after other rules like 'required', and only if they pass, so even when you click Save, if anything else fails validation, those errors will show, but the date error will not.

    In summary, date validation can only be tested by ensuring that all other rules pass and then clicking Save.

    0 讨论(0)
  • 2021-02-19 04:30

    Not 100% sure how it is in Yii2, but going out from Yii1 that had to look like this...

    array('org_datetime', 'date', 'format'=>'yyyy-M-d H:m:s'),
    

    (source: http://www.yiiframework.com/wiki/56/#hh8)

    ...I'd say i'd have to look something like this in Yii2:

    ['shopping_date', 'date', 'format' => 'yyyy-M-d H:m:s'],
    
    0 讨论(0)
  • 2021-02-19 04:42

    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!

    0 讨论(0)
提交回复
热议问题