Making regex for username and email address

For the username I guess it would be best to allow any order/combination of the following:


but NO spaces.

can’t think of anything else. maybe . too… can add that before the _ if I decide to include it.

$regex_username = [1]+$

would the above regex achieve this?

as for the email,

$regex_email = [2]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$

would that do the trick to allow any legit email?

just learning regex as we speak, so not sure if they are right.

  1. a-zA-Z0-9_- ↩︎

  2. a-zA-Z0-9._- ↩︎

I highly recommend using RegExr for testing out regular expressions.

As for your email question I personally use this:


While it will test the format, it can’t test if it’s legit, if you’re looking into that there are scripts out there that I believe test if a mail server is at that address or something like the sort.

If someone submits an illegal username such as abc123-& do you want to detect, inform and abort? (“sorry bad user, try again”) or do you want to correct, forgive and continue? (ie get rid of the & in this case)

For email address validation, unless you need to ‘special case’ anything, try leveraging PHP’s native [fphp]filter_var[/fphp] implementation. :slight_smile:

function is_valid_email($email){
  return false !== filter_var($email, FILTER_VALIDATE_EMAIL);

Zurev - Thanks, great to know there’s a site like that. And yeah I meant that I just want to check that the format is correct. I will be sending an email with a link for user validation, upon registration, once I figure out how (starts searching sitepoint, heh)

Cups - I have preg match set up and it’s currently throwing an error out if the username is invalid. The username regex I posted seems to be working good so far.

Anthony - Thanks, I will give that a shot - I guess that’s probably better to use than a regex anyway if I plan on sending a validation email?