4

是否可以在 yii2 客户端/ajax 验证中比较我下面表单中的开始和结束时间。

在此处输入图像描述

我的视图文件代码如下:

<?php foreach ($model->weekDaysList as $index => $value) : ?>
    <div class="row">
        <div class="col-sm-1">
        </div>
        <div class="col-sm-2">
            <?= $form->field($model, "[$index]td_day")->checkbox(['label' => $value]) ?>
        </div>
        <div class="col-sm-3">
            <?= $form->field($model, "[$index]td_from") ?>
        </div>
        <div class="col-sm-3">
            <?= $form->field($model, "[$index]td_to") ?>
        </div>
    </div>
<?php endforeach; ?>

控制器代码:

public function actionSchedule()
{
   $model = new TimetableDetails();
   $model->scenario = 'MultiSchedule';
   $model->attributes = Yii::$app->request->get('sd');

   if ($model->load(Yii::$app->request->post())) {
       if (Yii::$app->request->isAjax) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return \yii\widgets\ActiveForm::validate($model);
       }
   }    

   if (Yii::$app->request->isAjax) {
       return $this->renderAjax('schedule', [
             'model' => $model,
       ]);
   } else {
       return $this->render('schedule', [
             'model' => $model,
       ]);
   }
}
4

1 回答 1

1

您可以定义比较两个日期的规则。
首先,您需要将它们转换为整数才能使用集成验证器。最好的方法是在验证之前将日期转换为 unix 时间戳,并在验证之后转换为您需要的格式。
在您的模型中添加这些:

public function beforeValidate() {
    $this->td_to = strtotime($this->td_to);
    $this->td_from = strtotime($this->td_from);
    return parent::beforeValidate();
}

public function afterValidate() {
    $this->td_to = date(FORMAT, $this->td_to);
    $this->td_from = date(FORMAT, $this->td_from);
}

rules在您的方法中添加新规则

return [
    // rules
    ['td_to', 'compare', 'operator' => '<', 'type' => 'number', 'compareAttribute' => 'td_from', 'whenClient' => 'js:function () { /* validate values with jQuery or js here and if valid return true */ return true; }'],
];

这将适用于 ajax 验证。为了进行客户端验证,您需要添加js验证值并将其分配给whenClient规则键的函数。

于 2016-01-05T10:53:55.717 回答