如何在Yii 2中使用唯一验证

时间:2018-10-12 07:55:42

标签: validation yii2

我想使用户名和电子邮件地址唯一。

我正在使用yii base开发我的App。它对我不起作用。

Username and Email has already been taken

我的模特:

public function rules()
{
     return [
            [['username', 'email', 'password'], 'required'],
            [['username', 'email'], 'unique']
     ];
}

我的控制器:

public function actionCreate()
{
    $model = new Userapp();
    $post = Yii::$app->request->post('UserApp'); 
    if (Yii::$app->request->isPost && $model->validate()) {
        $model->email = $post['email'];
        $model->username = $post['username'];
        $model->password = $model->setPassword($post['password']);
        if($model->save()){
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }
    return $this->render('create', [
        'model' => $model,
    ]);
}

2 个答案:

答案 0 :(得分:0)

Yii2有很多内置的验证器see

其中一个是unique

来自Yii2文档。

  

// a1在以“ a1”属性表示的列中必须是唯一的

['a1', 'unique'],
     

// a1必须是唯一的,但是a2列将用于检查唯一性        的a1值

['a1', 'unique', 'targetAttribute' => 'a2'],

更新:

在您的规则数组中,将唯一验证器添加到emailusername中,如下所示:

public function rules()
{
     return [
        [['username', 'email', 'password'], 'required'],
        [['username', 'email'], 'unique'],
     ];

}

然后保存模型:

if(!$model->validate()){
   return false; 
} 

更新2:

您正在尝试在分配任何属性之前验证模型。将您的控制器代码更新为以下内容:

public function actionCreate()
{
    $model = new Userapp();
    $post = Yii::$app->request->post('UserApp'); 
        if (Yii::$app->request->isPost) {
             $model->email = $post['email'];
             $model->username = $post['username'];
             $model->password = $model->setPassword($post['password']);
            if($model->validate() && $model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            } 
            else {
                return false; 
             }
          }
   return $this->render('create', [
        'model' => $model,
   ]);
}

答案 1 :(得分:0)

这个想法是只有在 $model->save() 为真时才进行重定向,否则渲染回要创建/更新的原始模型