Yii Framework 2.0 Rules Date Validator

后端 未结 5 2140
情书的邮戳
情书的邮戳 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: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:

    
       field($model, 'inputfield_date')->textInput(); ?>
    
    

    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.

提交回复
热议问题