bhavika
bhavika

Reputation: 123

filter not working in yii2

I want to check if email has been already registered with different user by using validation rule exist. I wrote following code:

['email','exist',
'targetClass' => User::className(),
'targetAttribute' => 'email',
'message' => 'This email has already been taken. Please try another',
 'filter' => ['!=', 'user_id', Yii::$app->user->identity->id]],

It throws error every time, no matter if different user with the same email address exists or not. I want exact reverse validation from this code.

{
  "field": "email",
  "message": "This email has already been taken. Please try another"
}

Upvotes: 0

Views: 519

Answers (2)

Saleem Khan
Saleem Khan

Reputation: 150

May be you should also set unique and target class

['email', 'unique', 'targetClass' => '\common\models\User']

Upvotes: 0

Ripper
Ripper

Reputation: 1162

You want to use

['email', 'unique'],

Also in your database you can mark column as unique (at least for MySQL I am using).

It will check for unique records in specified column.

Upvotes: 4

Related Questions