javascript - Yii2:比较表格/数组输入中的开始和结束时间

标签 javascript php jquery yii2 yii2-validation

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

enter image description here

我的 View 文件代码是这样的:

<?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; ?>

Controller 代码:

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,
       ]);
   }
}

最佳答案

您可以定义一个规则来比较两个日期。
首先,您需要将它们转换为整数,以便能够使用集成验证器。最好的方法是在验证前将日期转换为 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 键。

关于javascript - Yii2:比较表格/数组输入中的开始和结束时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608619/

相关文章:

javascript - 分析我的 javascript 代码的最佳方法是什么?

javascript - 如何在 Node 模块中公开对象

javascript - 我如何使用 getOptions 检索 Jcrop 中的 truesize 数组值?

jquery - Cycle2 寻呼机禁用 Youtube 视频控件

javascript - ngRepeat 按深度属性过滤

php - PHP 中 MySQL 函数的奇怪语法错误

php - fatal error : Class 'NumberFormatter' not found

php - 如何使用 jquery 自动完成在 MySql 中加载大量记录

jquery - 从 Chrome 上的 tinymce 编辑器中删除 <p> 标签

javascript - 仅当 div 被隐藏时,如何在 div 上使用 angularjs $anchorScroll?