yii2 Validating Unique Value From Database : Unique Validation


Example

Some people have issues regarding error messages not being displayed if an existing value is being entered. For example I'm not allowing a user signup with an existing email.

View

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

Controller

<?php
use yii\web\Response; // important lines
use yii\widgets\ActiveForm; // important lines
        
.
.// Your code
.
        
public function actionSignup() 
{
            
    $modelUser = new User();
        
    //Add This For Ajax Validation 
    if(Yii::$app->request->isAjax && $modelUser->load(Yii::$app->request->post())){
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($modelUser);
    } 
    if ($modelUser->load(Yii::$app->request->post()) && $modelUser->save()) {
        return $this->redirect(['someplace nice']);
    }
    return $this->render('update', [
        'modelUser' => $modelUser,
    ]);            
}

Model

public function rules()
{
    return [
        ..............
        ['email', 'unique', 'message'=>'Email already exist. Please try another one.'],
        ...........
    ]
}