OctoberCMS 用户插件如何拒绝保留名称

OctoberCMS User Plugin How to Deny Reserved Names

我正在使用 User plugin

这是我关于如何拒绝用户名更改的

我有一个我不希望人们使用的保留名称列表(例如 admin、anonymous、guest)我需要放入一个数组中并在注册时拒绝。

我的自定义组件的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

        });

    });

}

我如何使用验证器来做到这一点?

我们可以使用 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 中的每个单词,如果找到则 returns false。否则 returns 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 中处理此问题。

你可以抛出异常来做到这一点

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')]);
        }

    });

});

}