Email Regular Expression

You might consider this a cynical view, but you should probably not try to implement a very strict email validation pattern with regular expressions. The fully compliant RFC-822 email regex is nothing to be trifled with; in fact, it is a behemoth.

As such, I recommend using only a simple regular expression for this task. And iIf you need to validate users email addresses, consider sending them a verification to confirm that what they have given you is correct, but if you really want to be strict about things – consider a pre-built validation package.

This tutorial is part of the course: “[[Regular Expressions]].”

The pattern:

^\S+@\S+\.\S+$           #just make sure that it "pretty much" looks like an email address
That’s it! A very simple regular expression to validate that an email address generally fits the form required – now email your user and make sure they receive it! See below for more specific validation techniques.

Validation in Java:

In Java, to be more comprehensive and accurate, you could use the following technique provided by the “javax.mail” specification:

Validating an email address with javax.mail
public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}

Validation in PHP

PHP also offers a built-in validation mechanism via the filter_var function.

Validating an email address with FILTER_VALIDATE_EMAIL
<?php
$email = "someone@exa mple.com";

if(!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
  echo "E-mail is not valid";
  }
else
  {
  echo "E-mail is valid";
  }
?>

References

http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address

Leave a Comment




Please note: In order to submit code or special characters, wrap it in

[code lang="xml"][/code]
(for your language) - or your tags will be eaten.

Please note: Comment moderation is enabled and may delay your comment from appearing. There is no need to resubmit your comment.