是否可以在 yii2 客户端/ajax 验证中比较我下面表格中的开始和结束时间。
我的 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/