Model unique validation condition


Can not seem to find the solution to my problem.

I would like to check for a value username and see if it exists in the database. So, I set a targetClass with works fine when I create a new record. However, when I edit an record and I try to save it, it says the username exists. So I want to add a condition that it should look for the given username where the id is not the id of my active record. How can I accomplish this? I use this code now:

public function rules()


    return [

        ['username', 'filter', 'filter' => 'trim'],

        ['username', 'required'],

        ['username', 'unique', 'targetClass' => '\backend\models\BackendUser', 'message' => Yii::t('backend','This username has already been taken.')],

        ['username', 'string', 'min' => 2, 'max' => 255],



Thanks for the help!

Eventually figured it out… with "targetAttribute" I was able to check the uniqueness.