我正在尝试对属性account_no
使用条件验证。只有在我在属性account_version
中选择值'old'时才应该验证。但它没有用。我得到的错误是new
也需要验证。我应该使用javascript来验证
我在模型中的代码
return [
['account_no', 'required', 'when' => function($model) {
return $model->account_version == 'Old';
}],
]
我的代码格式
<?php if ($model->isNewRecord) {?>
<div class="row">
<div class="col-md-2">
<label for="">Account Version</label>
</div>
<div class="col-md-2">
<?php echo $form->field($model, 'account_version')->radioList(['New'=>'New','Old'=>'Old'])->label(false); ?>
</div>
<div id="action_block" class="col-md-6">
<div class="col-md-3">
<label for="">Account No:</label>
</div>
<div class="col-md-3">
<?= $form->field($model, 'account_no')->textInput(['maxlength' => true])->label(false) ?>
</div>
</div>
</div>
<?php } ?>
答案 0 :(得分:0)
<?php
return [
['account_no', 'required', 'when' => function ($model) {
return $model->account_no == 'Old';
}, 'whenClient' => "function (attribute, value) {
return $('#account_no').val() == 'Old';
}"]
]
?>
http://www.yiiframework.com/doc-2.0/guide-input-validation.html [参考链接]
答案 1 :(得分:0)
<强>模型强>
[['account_no'], 'required', 'when' => function ($model) { return $model->account_version == 'Old'; }, 'whenClient' => "function (attribute, value) { return $('#modelName[account_version]').val() == 'Old'; }"],
<强>表格强>
<?php $form = ActiveForm::begin(['id' => 'account-form', 'enableAjaxValidation' => true]); ?>
<强>控制器强>
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);
}
}