简体   繁体   English

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

[英]Yii2 Implement client side unique validation for input field

I've one field in my big form ie 我的一个领域是我的大形式,即

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

Following is my ActiveForm options configuration: 以下是我的ActiveForm选项配置:

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

I want to implement client side unique validation for this. 我想为此实现客户端唯一验证。 I'm using unique validator for it but its only working for server side validation. 我正在使用唯一的验证器,但它只用于服务器端验证。

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

Other validations working perfectly but unique client side validation is not working. 其他验证工作完美但独特的客户端验证不起作用。

Finally I did it myself by enabling AJAX validation for a single input field and by using isAjax so that the server can handle the AJAX validation requests. 最后,我通过为单个输入字段启用AJAX验证并使用isAjax自行完成,以便服务器可以处理AJAX验证请求。

Following is the code: 以下是代码:

In view: 在视图中:

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

And in controller: 在控制器中:

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

It automatically calls validations rules defined in the Model. 它会自动调用模型中定义的验证规则。

For more info please refer : http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation 欲了解更多信息,请参阅: http//www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM