无线电盒

时间:2016-10-22 07:11:48

标签: validation yii yii2 conditional

我正在尝试对属性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 } ?>

2 个答案:

答案 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);
    }
}