十月CMS用户插件如何拒绝保留名称



我正在使用用户插件。

这是我之前关于如何拒绝用户名更改的问题。

我有一个我不希望人们使用的保留名称列表(例如管理员、匿名、来宾),我需要放入一个数组并在注册时拒绝。

我的自定义组件的插件.php

public function boot() {
RainLabUserModelsUser::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中每个单词的存在,如果找到任何单词,则返回 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 了解如何在10 月CMS中处理此问题。

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

public function boot() {
RainLabUserModelsUser::extend(function($model) {
$model->bindEvent('model.beforeSave', function() use ($model) {
$reserved = ['admin','anonymous','guest'];
if(in_array($model->username,$reserved)){
throw new OctoberRainExceptionValidationException(['username' => Lang::get('You can't use a reserved word as username')]);
}
});
});

}

最新更新