内部规则方法我有电子邮件规则:
['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 :(得分: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'],