PHP Email Validation Function

7th February 2008

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.

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

This can be used in the following way.

  1. $email = "[email protected]";
  2. if (validateEmail($email)) {
  3. echo 'Email valid!';
  4. }

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.