Skip to content

How To Prevent Spaces In WordPress Usernames

WordPress allows users to use spaces in their usernames, which is not a really great idea for the websites with open registrations. You wouldn’t want to confuse your users in spaces and stuff, so it’s a better idea to prevent spaces in WordPress username for the sake of your WordPress.

Non-technical users often pick a username with spaces and it’s so hard for them to remember their username. So, it’s your job to make this stuff easy for them & more neat for your database. You wouldn’t want someone to register twice to your website.

Just add following code snippet to your current theme’s functions.php file to prevent spaces in WordPress usernames:

add_filter('validate_username' , 'custom_validate_username', 10, 2);

function custom_validate_username($valid, $username ) {
		if (preg_match("/\\s/", $username)) {
   			// there are spaces
			return $valid=false;
		}

	return $valid;
}Code language: PHP (php)

1 thought on “How To Prevent Spaces In WordPress Usernames”

Leave a Reply

Your email address will not be published. Required fields are marked *