Simple Username Creation Validation with PHP

By  on  

When I create login areas (mostly intranets) for small websites, I'm always asked by the customer to keep usernames to letters and numbers. That means no email addresses as usernames and special characters like "_", "-", and ".". This, in my customer's mind, keeps the login easy for their users and limits the number of support calls they will receive. While I don't recommend disallowing common username characters like the ones cited above, I do understand their need for simplicity. Here's how, using PHP, I validate that a username is only letters and numbers.

The PHP

function validate_username($input,$pattern = '[^A-Za-z0-9]')
{
	return !ereg($pattern,$input);
}

It's as easy as that. I don't go as far as using this for passwords, but you could if you wanted to. I'll also mention that if I want to allow non-alphanumeric characters, I just need to change the function's pattern. Easy enough!

Recent Features

  • By
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    Create a Dynamic Table of Contents Using MooTools 1.2

    You've probably noticed that I shy away from writing really long articles. Here are a few reasons why: Most site visitors are coming from Google and just want a straight to the point, bail-me-out ASAP answer to a question. I've noticed that I have a hard time...

  • By
    Duplicate the jQuery Homepage Tooltips Using Dojo

    The jQuery homepage has a pretty suave tooltip-like effect as seen below: Here's how to accomplish this same effect using Dojo. The XHTML The above HTML was taken directly from the jQuery homepage -- no changes. The CSS The above CSS has been slightly modified to match the CSS rules already...

Discussion

  1. I like the approach — instead of matching a word boundary e.g. ^[a-zA-z0-9]*$ you match the first invalid character. I wonder what the speed difference is…

    BTW, you can use [^\w\d] insead ;) It’s lazier

  2. My bad. You cant use \w since it matches _ as well. On the other hand \w handles \d, so if you are looking for something quick for chars, digits and _ — you can use \w.

  3. Brian

    You could also use PHP’s ctype_alnum to match only alphanumeric characters
    which matches (ever so slightly) faster than its equivalent regular expression,
    and still retain future flexibility by using something like:

    function username($input, $pattern = false)
    {
           return ($pattern) ? !ereg($pattern, $input) : ctype_alnum($input);
    }
    

    Of course the speed difference is on the order of nanoseconds,
    but it is faster nonetheless.

  4. Jeff Hartman

    A better method name would be useful. ;)

  5. @Jeff: Ooops. I have this function within a class. I actually use it like this:

    if($valid->username($input)) {
      // move on...
    }
    

    I simply didn’t rename it for the blog. I’ll do that quick!

  6. A word of warning, ereg is being removed in PHP6 because of the more powerful and usually faster preg. Altering your code to work with pregs is easy and safer should the server you’re on upgrade to PHP6 sometime in the future:

    function validate_username($input, $pattern = '/[^A-Za-z0-9]/')
    {
        return !preg_match($pattern, $input);
    }
    
  7. ereg will be deprecated in php 5.3 and removed in 6, use preg instead

  8. ereg is not available in php 5.3.0

    any alternative for this ?

  9. Nolan Hawkins

    I’m rather new to regexp, and am just trying to get something exactly like this to work, but it just isn’t. I got annoyed, and then simplified as much as possible to this:


    and it isn’t responding anything except 0, no matter what I try.

  10. Nolan Hawkins

    Oops sorry. Anyways, it’s just a text input that posts to itself, and it deals with the post by doing

     if(!is_null($_POST["f"])){
    $input=$_POST["f"];
    $pattern = '[^A-Za-z0-9]';
    $a=preg_match($pattern,$input);
    echo $a;
    }
  11. The Best way I recommend is this :-

        $str = "";
        function validate_username($str) 
        {
            $allowed = array(".", "-", "_"); // you can add here more value, you want to allow.
            if(ctype_alnum(str_replace($allowed, '', $str ))) {
                return $str;
            } else {
                $str = "Invalid Username";
                return $str;
            }
        }
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!