Yii Tutorial on Yii AJAX Validation

the username validation should only be done on the server side because only the server has the needed information. in this case, you can use ajax-based validation.

step 1 − to enable the ajax validation, modify the registration view this way.

<?php
   use yii\bootstrap\activeform;
   use yii\bootstrap\html;
?>
  
<div class = "row">
   <div class = "col-lg-5">  
   
      <?php $form = activeform::begin(['id' => 'registration-form', 
         'enableajaxvalidation' => true]); ?>  
      <?= $form->field($model, 'username') ?>  
      <?= $form->field($model, 'password')->passwordinput() ?>  
      <?= $form->field($model, 'email')->input('email') ?>  
      <?= $form->field($model, 'country') ?>  
      <?= $form->field($model, 'city') ?>  
      <?= $form->field($model, 'phone') ?>  
      <div class = "form-group">             
         <?= html::submitbutton('submit', ['class' => 'btn btn-primary', 
            'name' => 'registration-button']) ?>
      </div>
      
      <?php activeform::end(); ?>  
   </div>
</div>

we should also prepare the server, so that it can handle the ajax requests.

step 2 − modify the actionregistration method of the sitecontroller this way.

public function actionregistration() { 
   $model = new registrationform(); 
   if (yii::$app->request->isajax && $model->load(yii::$app->request>post())) { 
      yii::$app->response->format = response::format_json; 
      return activeform::validate($model); 
   } 
   return $this->render('registration', ['model' => $model]); 
}

step 3 − now, go to http://localhost:8080/index.php?r=site/registration, you will notice that the form validation is done by ajax requests.

ajax requests