2017-04-04 18 views
1

我正在使用User pluginOctoberCMS用戶插件如何拒絕保留名稱

這是我的previous question關於如何拒絕用戶名更改。

我有一個保留名稱列表,我不希望人們使用(如管理員,匿名,客人)我需要放入一個數組並拒絕註冊。

我的自定義組件的Plugin.php

public function boot() { 

    \RainLab\User\Models\User::extend(function($model) { 

     $model->bindEvent('model.beforeSave', function() use ($model) { 

      // Reserved Names List 
      // Deny Registering if Name in List 

     }); 

    }); 

} 

我會怎麼做,使用驗證?

回答

2

可以拋出一個異常,要做到這一點

public function boot() { 

\RainLab\User\Models\User::extend(function($model) { 

    $model->bindEvent('model.beforeSave', function() use ($model) { 

     $reserved = ['admin','anonymous','guest']; 

     if(in_array($model->username,$reserved)){ 
      throw new \October\Rain\Exception\ValidationException(['username' => \Lang::get('You can't use a reserved word as username')]); 
     } 

    }); 

}); 

}

+0

我相信它是工作。這簡化了過程。 –

+0

很高興這有幫助。 –

5

我們可以通過Validator::extend():

Validator::extend('not_contains', function($attribute, $value, $parameters) 
{ 
    // Banned words 
    $words = array('a***', 'f***', 's***'); 
    foreach ($words as $word) 
    { 
     if (stripos($value, $word) !== false) return false; 
    } 
    return true; 
}); 

上面的代碼定義名爲not_contains驗證規則創建驗證規則 - 它看起來在域值$words每個字的存在,如果發現任何返回false。否則,它返回true以表示驗證通過。

然後,我們可以用我們的規則爲正常:

$rules = array(
    'nickname' => 'required|not_contains', 
); 

$messages = array(
    'not_contains' => 'The :attribute must not contain banned words', 
); 

$validator = Validator::make(Input::all(), $rules, $messages); 

if ($validator->fails()) 
{ 
    return Redirect::to('register')->withErrors($validator); 
} 

還檢查了這一點https://laravel.com/docs/5.4/validation#custom-validation-rules知道如何在OctoberCMS處理這個。

+0

我在維護模式的網站,而在發展,但我可以看到它,而在後臺記錄。當我擴展驗證器並將其放入boot()時,它將我鎖定在後端並進入維護模式頁面。 –

+0

我把它放在關於規則的模型中。我得到錯誤「分析錯誤:語法錯誤,意外'驗證'(T_STRING),期望函數(T_FUNCTION)」。我如何在模型中包含驗證器?我試過'使用Validator'和'使用Illuminate \ Validation \ Validator'。 –

+0

檢查https://laravel.com/docs/5.4/validation#custom-validation-rules –