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.