Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Implement client side unique validation for input field

I've one field in my big form i.e.

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

Following is my ActiveForm options configuration:

<?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.

like image 703
J.K.A. Avatar asked Nov 03 '15 04:11

J.K.A.


1 Answers

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.

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

like image 74
J.K.A. Avatar answered Nov 15 '22 00:11

J.K.A.