Browse Source

改善前台用户设置防止昵称重复

F4NNIU 5 years ago
parent
commit
568fd153ad

+ 7 - 1
application/api/controller/User.php

@@ -158,7 +158,13 @@ class User extends Api
             }
             $user->username = $username;
         }
-        $user->nickname = $nickname;
+        if ($nickname) {
+            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
+            if ($exists) {
+                $this->error(__('Nickname already exists'));
+            }
+            $user->nickname = $nickname;
+        }
         $user->bio = $bio;
         $user->avatar = $avatar;
         $user->save();

+ 17 - 0
application/api/controller/Validate.php

@@ -54,6 +54,23 @@ class Validate extends Api
     }
 
     /**
+     * 检测昵称
+     *
+     * @param string $nickname 昵称
+     * @param string $id       排除会员ID
+     */
+    public function check_nickname_available()
+    {
+        $email = $this->request->request('nickname');
+        $id = (int)$this->request->request('id');
+        $count = User::where('nickname', '=', $email)->where('id', '<>', $id)->count();
+        if ($count > 0) {
+            $this->error(__('昵称已经被占用'));
+        }
+        $this->success();
+    }
+
+    /**
      * 检测手机
      *
      * @param string $mobile 手机号

+ 1 - 0
application/api/lang/zh-cn/user.php

@@ -11,6 +11,7 @@ return [
     'Password must be 6 to 30 characters'   => '密码必须6-30个字符',
     'Mobile is incorrect'                   => '手机格式不正确',
     'Username already exist'                => '用户名已经存在',
+    'Nickname already exist'                => '昵称已经存在',
     'Email already exist'                   => '邮箱已经存在',
     'Mobile already exist'                  => '手机号已经存在',
     'Username is incorrect'                 => '用户名不正确',

+ 1 - 1
application/index/view/user/profile.html

@@ -59,7 +59,7 @@
                         <div class="form-group">
                             <label class="control-label col-xs-12 col-sm-2">{:__('Nickname')}:</label>
                             <div class="col-xs-12 col-sm-4">
-                                <input type="text" class="form-control" id="nickname" name="nickname" value="{$user.nickname|htmlentities}" data-rule="required" placeholder="">
+                                <input type="text" class="form-control" id="nickname" name="nickname" value="{$user.nickname|htmlentities}" data-rule="required;remote({:url('api/validate/check_nickname_available')}, id={$user.id})" placeholder="">
                             </div>
                         </div>
                         <div class="form-group">