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!
- August 29, 2008
- article by Gabriel C.
- 2 comments
Related Posts
-
Validate (input) passwordat August 30, 2008 with 2 comments
-
PHP: How to validate e-mail addresses using regular expressionsat May 21, 2008 with 2 comments
-
PHP: Using the string concatenationat September 6, 2008 with 2 comments
-
PHP: How to validate a telephone numberat September 24, 2008 with 2 comments
-
How to extract username from an e-mail address stringat September 5, 2008 with 2 comments

2 Replies to "Validate (input) username"
December 10, 2009 at 8:59 PM
Hi thanks for the code. i’m just found this blog via google. have fun. keep coding
February 7, 2010 at 5:35 PM
Yeah thanks form the simple code, copy and paste and works fantastic.