Enforce Alphanumeric Usernames in WordPress Registration
25
March
To kick things off, here’s a neat trick I recently figured out. One of my clients needed to enforce alphanumeric usernames so that users couldn’t enter email addresses and such as valid usernames. Turns out there’s a nice filter validate_username which does the trick nicely. You may need to customize the regex expression but here’s the principle of the thing:
// Only allow alphanumeric and underscores in username
add_filter('validate_username' , 'custom_alphanumeric_usernames', 1, 2);
function custom_alphanumeric_usernames($valid, $username ) {
if ($valid) {
if (preg_match("/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/", $username)) {
return true;
}
}
return false;
}
No comments yet.