Yii2 Implement unique client-side validation for input field

I have one field in my big form.

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

The following is the configuration of ActiveForm settings:

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

I want to implement a unique client-side validation for this. I use a unique validator for it, but it only works for server-side validation.

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

Other checks are functional, but a unique client-side check does not work.

+4
source share
1 answer

Finally, I did this myself, enabling AJAX validation for a single input field and using isAjax so that the server can handle AJAX validation requests.

Below is the code:

In sight:

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

And in the 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;
    }
}

, .

. http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation

+3

Source: https://habr.com/ru/post/1614219/


All Articles