Vinod Kumar
Vinod Kumar

Reputation: 21

Avoid "Username already exixts" error for username validation while updating the form in yii2

I have a form for user creation and I will check the existing username from one of our API and I make a rule with custom validation function and its working fine. But while updating the form, the custom function also runs and displays the error "Username already exists" with my username.

My Rules

public function rules()
{
    return [
        ['username', 'trim'],
        ['username', 'uniqueUsers'], // Find username already exists
    ]
}

My Custom validation function,

public function uniqueUsers($attributes, $params) 
{
    $getUser = Yii::$app->params['user']."?username=".$this->username;
    $validUsername = BaseModel::getDetails($getUser);
    $getUserValue = isset($validUsername['display']) ? $validUsername['display'] : '';
    if($getUserValue!='') {
        // echo "$attributes/";
        $this->addError($attributes, 'Username Already Exists');
    }
}

Here what I want is, I have used the same username the function won't run but I have changed again then need to call that function for check unique.

Upvotes: 0

Views: 142

Answers (3)

Govind
Govind

Reputation: 267

You can use this too

['username', 'unique', 'when' => function($model) {
                            return $model->isAttributeChanged('username');
                        }],

or go through with @Hakeem Nofal suggestions

Upvotes: 3

Erdem Medre
Erdem Medre

Reputation: 41

You can do this with using scenario;

['username', 'uniqueUsers', 'on'=>'create']

or checking the model is new.

public function uniqueUsers($attributes, $params) 
{
    if ($this->isNewRecord){
        // Your validation controls
    }
}

Upvotes: -1

Hakeem Nofal
Hakeem Nofal

Reputation: 149

check out the yii2 own unique validator

https://www.yiiframework.com/doc/api/2.0/yii-validators-uniquevalidator

// a1 needs to be unique
['a1', 'unique']

// a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
['a1', 'unique', 'targetAttribute' => 'a2']
// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]

for you case it might look like

['username', 'unique', 'message' => Yii:t('app','Username Already exists')]

Upvotes: 1

Related Questions