除了Yii2中当前用户的用户名外,如何在表“用户”中唯一的字段“用户名”检查

Lin*_*ink 2 validation yii2

在视图中,我的字段username始终由当前用户的用户名填充。并且它总是(在提交时)将用户名值发送到我的InformationForm并验证它的唯一性,如下所示:

[['username'], 'unique', 'targetAttribute' => 'username', 'targetClass' => '\common\models\User', 'message' => 'This username can not be taken.'],
Run Code Online (Sandbox Code Playgroud)

它说这个用户名已经被占用了。所以我想在username那时检查我的值,它不是我的用户名。这就像我在数据库中的当前用户名 -> Bob 我在字段中查看的值username-> Bob 我点击Submit它不应该检查这个用户名是否是唯一的(显然是因为它是我的用户名)

就在那时,当我在数据库中的当前用户名 -> Bob 和字段中的视图值username-> John 并且我点击时Submit- 应该检查这个用户名是否是唯一的

我知道“自定义验证器”,所以我可以在我的InformationForm. 而且我想找到如何完成我在这里写的所有内容,除了在我的InformationForm.

Tha*_*hPV 5

您可以将when属性用于unique验证器。

你在模型中的规则是:

[
    ['username'], 'unique', 
    'targetAttribute' => 'username', 
    'targetClass' => '\common\models\User', 
    'message' => 'This username can not be taken.',
    'when' => function ($model) {
        return $model->username != Yii::$app->user->identity->getUsername(); // or other function for get current username
    }
],
Run Code Online (Sandbox Code Playgroud)

可以参考yii2文档:http ://www.yiiframework.com/doc-2.0/yii-validators-validator.html#$when-detail

祝好运并玩得开心点!