I'm copying this all in one place since it's always so difficult to find it through the search and the other examples floating around aren't all compatible with the latest Flarum.
The default array of rules that are being looped through can be seen in https://github.com/flarum/core/blob/master/src/User/UserValidator.php Extensions might also add or remove rules, so when the custom extender runs the rules might actually be different from what you see on GitHub. The code example is made in a way that won't crash it the rule it's looking for cannot be found.
The following has been tested with Flarum 1.1
Example 1: change username regex and min length
Warning: changing username regex can break profile URLs or mentions if you allow more characters than Flarum initially allows. Flarum also has a custom validation message for the regex rule which explains the formatting, so you might want to edit that validation message as well if you have changed the allowed characters.
Other warning: don't change the max length to a value bigger than the database column size! If you do your users will experience 500 errors instead of the validation error.
<?php
use Flarum\Extend;
return [
(new Extend\Validator(\Flarum\User\UserValidator::class))
->configure(function ($flarumValidator, $validator) {
$rules = $validator->getRules();
// The validator is sometimes used to validate *only* other attributes, in which case the username rule won't be present. We can skip this situation by returning early
if (!array_key_exists('username', $rules)) {
return;
}
// Loop through all Laravel validation rules until we find the one we're looking to replace
$rules['username'] = array_map(function (string $rule) {
// Example regex change: allow dots in usernames
if (\Illuminate\Support\Str::startsWith($rule, 'regex:')) {
return 'regex:/^[.a-z0-9_-]+$/i';
}
// Example min length change
if (\Illuminate\Support\Str::startsWith($rule, 'min:')) {
return 'min:10';
}
// If it's not one of the rules we're looking for, we keep it as-it
return $rule;
}, $rules['username']);
$validator->setRules($rules);
}),
];
Example 2: change minimum password length
<?php
use Flarum\Extend;
return [
// Register extenders here to customize your forum!
(new Extend\Validator(\Flarum\User\UserValidator::class))
->configure(function ($flarumValidator, $validator) {
$rules = $validator->getRules();
// The validator is sometimes used to validate *only* other attributes, in which case the password rule won't be present. We can skip this situation by returning early
if (!array_key_exists('password', $rules)) {
return;
}
// Loop through all Laravel validation rules until we find the one we're looking to replace
$rules['password'] = array_map(function (string $rule) {
if (\Illuminate\Support\Str::startsWith($rule, 'min:')) {
return 'min:16';
}
// If it's not one of the rules we're looking for, we keep it as-it
return $rule;
}, $rules['password']);
$validator->setRules($rules);
}),
];