vuelidate 結合 Laravel 後端資料註冊驗證

GeekGhc發表於2017-07-27

介紹

在實現vuelidate基本的驗證之後 我們需要去真正實現專案中的註冊登入以及我們的驗證流程

有的具體的程式碼我也會放到我的gist上面

後端api以及資料準備

對於前端的請求 以laravel作為後端專案需要對資料進行處理和相應的反饋

我們可以先去建立User Model在專案終端:

$ php artisan make:model User -m

生成Model後就去定義好欄位資訊:

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->string('avatar');//儲存使用者頭像
            $table->string('confirm_code',64);//郵箱確認啟用code
            $table->smallInteger('is_confirmed')->default(0);//判斷使用者呢是否已經啟用他的郵箱
            $table->integer('followers_count')->default(0);
            $table->integer('followings_count')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
 }

我們也可以嘗試建立對應的Factory然後可以生成測試資料:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'avatar' => $faker->imageUrl(256, 256),
        'confirm_code' => str_random(48),
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

寫好模型工廠後我們可以試著生成幾個測試資料 專案終端:

$ php artisan tinker;
$ namespace App;
$ factory(User::class,4)->create()

現在我們已經準備好測試資料 當然你也可以使用註冊過後的資料

開始註冊之前先去生成對應的Controller

我的laravel後端專案是5.4 而在5.4裡面新增了控制器與模型的繫結

在專案終端執行:

$ php artisan make:controller UserController --model=User

生成控制器後就去路由定義我們的路由方法:

Route::group(['prefix'=>'user','middleware'=>['api','cors']], function () {
    Route::post('/register','UserController@store');
});

UserController裡面的具體邏輯就是平常的註冊邏輯:

public function store(Request $request)
    {
        $data = [
            'avatar' => '/images/avatar/default.png',
            'confirm_code' => str_random(48),
        ];
        $user = User::create(array_merge($request->get('user'),$data));
        return json_encode(["user_id"=>$user->id,"status"=>"success"]);
 }

這樣就可以完成註冊的後端處理邏輯

vue基於後端api資料進行資料檢驗

我們的template內容基本還是那樣的判斷方式 只不過在這裡我對欄位的唯一性的針對使用者名稱和郵箱

所以我的具體validations是這樣的:

validations: {
    newUser:{
       name: {
            required,
            minLength: minLength(4),
            async isUnique (value) {
               if (value === '') return true
               const response = await fetch(`http://localhost:8000/api/unique/name/${value}`)
               return Boolean(await response.json())
            }
       },
       email: {
            required,
            email,
            async isUnique (value) {
               if (value === '') return true
               const response = await fetch(`http://localhost:8000/api/unique/email/${value}`)
               return Boolean(await response.json())
            }
       },
       password: {
           required,
           minLength: minLength(6)
       },
       confirm_pwd: {
            required,
            sameAsPassword: sameAs('password')
       }
    }
},

當然這只是對欄位檢驗的要求 後端的檢驗路由方法:

Route::group(['prefix'=>'unique','middleware'=>['api','cors']], function () {
    Route::get('/name/{value}','ValidateController@ValidateName');
    Route::get('/email/{value}','ValidateController@ValidateEmail');
});

這裡我是單獨生成了一個Controller去實現方法邏輯

對於使用者名稱的檢驗:

public function ValidateName($name)
    {
        $res = User::where("name",$name)->count();
        if($res){
            return response()->json(false);
        }
        return response()->json(true);
}

當然對於郵箱的檢驗也是一樣的

這些完成後我們再去前端完成我們的註冊方法應該就差不多可以了 但其實並不是

因為註冊的前提的是每個欄位都符合要求 這樣才可以去進行註冊這個邏輯

所以在註冊按鈕新增方法:

<div class="control-group">
    <button
            class="btn btn-primary btn-lg btn-block btn-login-register"
            @click="register($v.newUser)"
    >立即註冊
    </button>
</div>

這裡的$v.newUser其實就是所有被檢驗資料的集合 因為我的data是這樣被宣告的:

 data(){
    return{
        newUser: {
            name:'',
            email:'',
            password:'',
            confirm_pwd:''
        },
    }
},

這樣完成好後 最終的註冊邏輯被我放在了register function裡面

register:function(value){
    value.$touch();//驗證所有資訊
    if(!value.$error){
        this.axios.post('http://localhost:8000/api/user/register',{user:this.newUser}).then(response => {
          console.log("data = "+response.data.status)
        })
    }
}

這裡的value.$error是對所有欄位的$error的或的結果 只有所有欄位的$errorfalse時 才能通過檢驗進行下一步的註冊

value.$touch() 其實是執行的設定其$dirtytrue這些在文件上也都有介紹

這樣我們去走一下整個的註冊流程

  • 使用者註冊
    first

我們已經註冊過了以為jason的使用者

  • 資料檢驗
    second

資料連結

相關文章