[Previous] [Contents] [Next]


Validating Usernames


When a new user is creating an account with our system, we might require the user to create a new username. We often place a number of restrictions on this username, such as that it must consist entirely of alphanumeric characters (that is, ASCII letters and numbers only), must not contain punctuation or whitespace, and must be between 8 and 50 characters long.

The regular expression for this turns out to be pretty simple: [[:alnum:]]{8,50}. If we want to relax our restrictions a little bit and allow a few other characters in usernamesnamely spaces, underscores (_), and dashes (-)we can change the regular expression to [[:alnum:] _-]{8,50}.

We can then use the ereg function to actually make sure that a username conforms to this pattern, as follows:

<?php

  $valid = ereg($_POST['user_name'], '[[:alnum:] _-]{8,50}');
  if (!$valid)
  {
    // show error saying username is invalid ...
  }

?>


[Previous] [Contents] [Next]