Yii2实现输入字段的客户端唯一验证


Yii2 Implement client side unique validation for input field

我的大表单中有一个字段,即

<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>

以下是我的ActiveForm选项配置:

<?php
$form = ActiveForm::begin([
            //'id' => 'printerForm',                
            'enableClientValidation' => true,
            'options' => [
                'enctype' => 'multipart/form-data',
            ]
]);
?>

我想实现客户端对此的唯一验证。我为它使用了唯一的验证器,但它只适用于服务器端验证。

public function rules() {
        return [
     [['name'], 'unique'],
]
...
other validations
...
};

其他验证工作正常,但唯一的客户端验证不起作用。

最后,我自己完成了这项工作,为单个输入字段启用了AJAX验证,并使用isAjax使服务器可以处理AJAX验证请求。

以下是代码:

视图:

<?= $form->field($model, 'name',['enableAjaxValidation' => true, 'validateOnChange' => false])->textInput(['maxlength' => 255]) ?>

在控制器中:

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            $nm= $_POST['BusinessProcessProfile']['name'];
            $result = Model::find()->select(['name'])->where(['name' => "$nm"])->one();
            if ($result) {
                Yii::$app->response->format = 'yii'web'Response::FORMAT_JSON;
                return 'yii'widgets'ActiveForm::validate($model, 'name');
            } else {
                return false;
    }
}

它自动调用在模型中定义的验证规则。

有关更多信息,请参阅:http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-侧面验证