Validate (input) username

Posted on August 29, 2008, under PHP,  Bookmark it

Hello coders,

Here’s a function that validates a username. It can be used when you have a register form and the user should enter a valid username (that shouldn’t contain illegal characters).

<?php
function validate_username($username)
{
$check = eregi_replace('([a-zA-Z0-9_]+)', "", $username);

if(empty($check))
	{
	return true;
	}
	else
	{
	return false;
	}
}

$username = 'john_jones';

$validator = validate_username($username);

if($validator)
{
echo 'The username is valid.';
}
else
{
echo 'The username should contain only letters, numbers and underscores.';
}
?>

If you use ‘john#_$%jones’ as an username the function will return ‘false’.

If you have any comments / suggestions feel free to post them.

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Related Posts

2 Replies to "Validate (input) username"

  1. Hi thanks for the code. i’m just found this blog via google. have fun. keep coding

  2. Yeah thanks form the simple code, copy and paste and works fantastic.

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)