PHP Email Validation Function

Every time you accept any input from a use you should attempt to validate it. This is to stop users trying to break the site and also corrects silly mistakes that users might introduce to their input.

Before sending off an email to a new user congratulating them on signing up it is best to validate that email address. Here is function that does this.

function validateEmail($email)
{
  $reg_exp = '/^[A-z0-9][\w.-]*@[A-z0-9][\w\-\.]+\.[A-z0-9]{2,3}$/';
  if (preg_match($reg_exp, $email) == true) {
    return true;
  } else {
    return false;
  }
}

This can be used in the following way.

$email = "[email protected]";
if (validateEmail($email)) {
  echo 'Email valid!';
}

The regular expression used here seems to work with most email addresses. If you mind you are having trouble then have a look at the email section in the Regular Expressions Library. You could convert this function to check for anything that you like by using any regular expression that you want just by changing the $reg_exp variable.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 12 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.