blog.autopsy.se

basically; it sucks. everything sucks. but.. in a good way..

validating user names sucks!

You know when you're writing any application, and you want to restrict the characters in the user name? Instead of checking for non allowed characters, look for allowed. Sounds strange? Not really, you'll understand:

function checkname($string, $allowed) {
$allowed = "/[$allowed]/s";
$string = preg_replace($allowed, "", $string);
if ( $string )
return FALSE;
else
return TRUE;
}

So what you'll do is remove all allowed characters, and if there are any left in the string the user has chosen an invalid username. Ofcourse it's regexp that does the trick. Using the code:

if ( ! checkname($input, "A-Za-z0-9_\.") )
echo "Invalid username!";
else
echo "Ok, lets go!

We're allowing A-Z, a-z, 0-9, underscore and dots in the username.

posted by ube in PHP and have No Comments

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment