yii2 Validate unique value from database in Yii2


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.'],