Validate Email Addresses

Here’s one way to validate email addresses using the regular expression I found online that works great for me. You can use this little piece of PHP code in your forms or just about any place you need it. The regular expression should be typed in one continuous line, but I added a couple of line breaks for legibility purposes, in this example. You can also place this code  inside a function, so you can use it repeatedly by simply calling the function, in this case, validate_email(). If you have a better regular expression for validating email addresses, please share.

The Code

if (!eregi("
  ^[_a-z0-9-]+(\.[_a-z0-9-]+)*
  @[a-z0-9-]+(\.[a-z0-9-]+)*
  (\.[a-z]{2,3})$", $email)):
 echo "Invalid email.";
else:
 echo "Valid Email.";
endif;

The Function

function validate_email($email) {
 if (!eregi("
   ^[_a-z0-9-]+(\.[_a-z0-9-]+)*
   @[a-z0-9-]+(\.[a-z0-9-]+)*
   (\.[a-z]{2,3})$", $email)):
  echo "Invalid email.";
 else:
  echo "Valid Email.";
 endif;
}

2 thoughts on “Validate Email Addresses

Comments are closed.