It has come to my attention that my script above has an issue.
When validating only some of the user properties, the validator will be loaded only with the rules to validate. So for example when you edit the user groups or email via the user edit modal, the UserValidator will be used but will not contain a username rule.
This would be the correct code to account for that:
<?php
use Flarum\Extend;
use Flarum\Foundation\Event\Validating;
use Flarum\User\UserValidator;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;
return [
// Register extenders here
new Extend\Compat(function(Dispatcher $events) {
$events->listen(Validating::class, function(Validating $event) {
if ($event->type instanceof UserValidator) {
$rules = $event->validator->getRules();
if (!array_key_exists('username', $rules)) {
return;
}
$rules['username'] = array_map(function(string $rule) {
if (Str::startsWith($rule, 'regex:')) {
return 'regex:/^[.a-z0-9_-]+$/i';
}
if (Str::startsWith($rule, 'min:')) {
return 'min:10';
}
return $rule;
}, $rules['username']);
$event->validator->setRules($rules);
}
});
}),
];