2015-06-19 22 views
0

規則方法我有這樣的規則,電子郵件:Yii2 - 自定義功能獨特的電子郵件

['email', 'uniqueEmail'], 
['email', 'email'], 

和uniqueEmail方法:

public function uniqueEmail($attribute, $email) 
    { 
     $user = static::findOne(['email' => Yii::$app->encrypter->encrypt($email)]); 
     if (count($user) > 0) 
      $this->addError($attribute, 'This email is already in use".'); 
    } 

電子郵件驗證工作,但uniqueEmail是不工作。我怎樣才能做到這一點?

回答

0

爲什麼你認爲$email與填充該值?作爲由文檔所述,第二函數參數是實際參數陣列,在驗證器聲明(['email', 'uninqueEmail', 'param1' => 'value1', 'param2', 'value2'])

的端部供給的嘗試這種情況:

public function uniqueEmail($attribute) { 
    $user = static::findOne(['email' => Yii::$app->encrypter->encrypt($this->{$attribute})]); 
    if ($user) { // dont use count($user) - if it's there, it's a single object, you want to check if it's not null! 
     $this->addError($attribute, 'This email is already in use".'); 
    } 
} 

Yii2它接受申報的ad-hoc審定匿名函數:

['email', function($attribute) { 
    $user = static::findOne(['email' => Yii::$app->encrypter->encrypt($this->{$attribute})]); 
    if ($user) { 
     $this->addError($attribute, 'This email is already in use".'); 
    } 
}], 
['email', 'email'], 
+0

想你的代碼(第二種方法),但驗證仍然沒有工作:/ – Sasha

+0

@Sasha請告訴你什麼是「不工作」的意思是你有一個記錄,在該表中。 ,有'電子郵件'字段的值與您查找的加密電子郵件的值相同?你有任何錯誤,你可以做一個'var_dump($ user);在驗證器中退出?我只是修復了一個明顯的問題,我無法猜測你的數據庫是如何建模的,或者你的應用程序如何工作。 – ddinchev

+0

在db中有一條加密郵件的記錄。我必須糾正自己--JS部分無法正常工作(現場驗證,無需發佈表單),但是一旦發佈了該表單,驗證就可以正常工作。 – Sasha