Data Validation with Regular Expressions

One of the best ways to get a better feel for how regular expressions work is to see some examples and to try them for ourselves. In this section, we use some of the data validation tasks in our web applications to demonstrate how we can use regular expressions to perform these tasks.

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 usernames namely 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:

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