validation method in a model class

Hello everybody.

How can I correctly write my own validation method in my model class?

Namely I need a method that would check if the record with the name submitted from the form already exists in my database. If it exists then submitted data must be considered invalid.

Thank you.

Read this (particularly the paragraph "Declaring validation rules"):

I read it but I don’t quite understand how to pass data to the method and what the method should return.

You don’t need your own method. Yii already has something for you:

  // in your rules() add:

  array('yourattribute', 'unique', 'message'=>'Value already exists'),

This is how a custom function in model can look like:

	public function uniqueUsername($attribute, $params)


		$user = User::model()->find(

			"LOWER(`username`) = :username COLLATE utf8_bin",

			array(':username' => strtolower($this->username),



		if (null !== $user)


			$this->addError('username', $params['message']);



And rule:

array('username', 'uniqueUsername', 'message' => 'something'),

Thank you all. :)

I can’t use ‘unique’. In my database table I have two fields: ‘oblid’ and ‘misto’. I have to validate ‘misto’. In my database there should be no two same mistos with the same ‘oblid’, but there can be many the same mistos with different oblids.