yii2 Validation Validate unique value from database in Yii2

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Few people have issue regarding error message not displaying if existing value is being entered in textbox.

So, For Example I'm not allowing user to enter existing email.

signup.php

(Page where you wanted to sign up new user without existing email id)

  1. Remove use yii\bootstrap\ActiveForm; (if present)
  2. Add use yii\widgets\ActiveForm;
  3. Add 'enableAjaxValidation' => true (In that field Where you want to stop user for entering existing email id.)
<?php
use yii\bootstrap\ActiveForm;
use yii\widgets\ActiveForm;
?>

<?= $form->field($modelUser, 'email',['enableAjaxValidation' => true])
    ->textInput(['class'=>'form-control','placeholder'=>'Email']); ?>

Controller

Add these lines on top use yii\web\Response;use yii\widgets\ActiveForm;

<?php
use yii\web\Response;
use yii\widgets\ActiveForm;

  .
  .// Your code
  .

  public function actionSignup() {
    
    $modelUser = new User();

    //Add This For Ajax Email Exist Validation 
    if(Yii::$app->request->isAjax && $modelUser->load(Yii::$app->request->post())){
      Yii::$app->response->format = Response::FORMAT_JSON;
      return ActiveForm::validate($modelUser);
    } 
    else if ($model->load(Yii::$app->request->post())) {
      
    }
    
  }
?>

Model

[['email'],'unique','message'=>'Email already exist. Please try another one.'],


Got any yii2 Question?