Best approach for checking if email is already used by another person

Hi guys!

Which is the best approach to perform a check whether certain email is already in DB and thus detect attempts of users to register again with it.

I would rather use it in the same way as validation rules(I mean it should appear in the box with errors.

Additionally, I am planning to perform AJAX request, so that I inform the user just in time.


If you are using AR you can use the built in validation rule unique.

Like this:


  public function rules()


    return array(array('email', 'unique'));



Where email is the name of the column for email in your database table.

Thanks, man. This was what I was looking for.

No worries

If I may add something, take care that when the user wants to update his/her email, the 'unique' validator is not appropriate and you could use a scenario based rule like for instance :

(example below would be for a name update …but the principle is tha same than for email)

array('name', 'ValidateUniqueName','attributes'=>'name', 'on' => 'update')

where ValidateUniqueName would be defined as a method:

public function ValidateUniqueName($attribute,$params)


	$exist=User::model()->exists('name=:name and id!=:ID',	


			':name' => $this->name,

			':ID'   => $this->id





		$this->addError($attribute,'this name is already used');



I think this is the correct way to handle this situation and as I had to deal with it already, thought it may be useful to you.



Would you mind if I ask the difference between the two? I am not sure you allow two users (having the different id) having the same e-mail address.

:-[ oups ! you’re right … I was so focused on how to use scenario based rules that I didn’t noticed it was not useful here.  ;D ;D

Thank you Mocapapa for pointing it out



Pheeew, thanks for clearing this out guys. I was really confused about Raouls post and thought that I had missed something.

Hmm. Now i am confused  :). Didn’t use scenario based validation, but from my understanding i found Raoul’s tipp reasonable. As there are 2 scenarios:

  1. User registers: email must be unique among all users in db.

  2. User updates his information (but doesn't change his email): email must be unique among all users except himself.

Isn't that, what Raoul's post was about?

If the column being validated is not a PK, you can use the unique validator for both scenarios.

Yes, what you discuss is right. Actually I was getting errors when updating. However, I think the problem is related to the fact that I copied the create action code into the update action because I deleted it initially by thinking I am editing the create action. Now, I am having informatics class at school, so I can't check the code at home, so will check it and provide my feedback. Actually, it would be good if I am able to use action-based validators.