Solved

Email Validation

Posted on 2010-09-21
8
786 Views
Last Modified: 2013-12-26
Hi,

I need some help with improving an email validation script, any input will be highly appreciated. Thank you.

#!/usr/bin/perl
use Data::Dumper;

%lookup_cache = ();

sub valid_address {
  my($addr) = @_;
  my($domain, $valid);

  # Lower-case address
  $addr = lc($addr);

  # Validate format of address
  return(0) unless ($addr =~ /^[^@]+@([-\w]+\.)+[a-z]{2,4}$/);

  # Grab domain
  $domain = (split(/@/, $addr))[1];

  # Lookup and return cached result if it exists
  $cached_result = $lookup_cache{$domain};
  if ($cached_result ne '')
  {
    print "[cached_result] ";
    return $cached_result;
  }

  # Do domain lookup
  $valid = 0;
  if (open(DNS, "nslookup -q=any $domain |"))
  {
    while (<DNS>) {
      $valid = 1 if (/^$domain.*\s(mail exchanger|internet address)\s=/i);
    }
  }

  # Store cached result for later
  $lookup_cache{$domain} = $valid;

  return $valid;
}

while (<>) {
  $addy = $_;
  $addy =~ s/\s+$//;
  if ($addy)
  {
    print "$addy " . (valid_address($addy) ? 'valid' : 'invalid') . "\n";
  }
}
0
Comment
Question by:faithless1
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 12

Expert Comment

by:Rant32
ID: 33723610
Perl has a module for that: Email::Valid

http://search.cpan.org/~rjbs/Email-Valid-0.184/lib/Email/Valid.pm

Hope this helps.
0
 
LVL 3

Expert Comment

by:Progressed
ID: 33723923
jquery has that build in... you could take a look at:

http://flowplayer.org/tools/demos/index.html

You can download a prepacked JS with builtin Jquery. its much easier!
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 33725110
This function has always served me well.  HTH, ~Ray
<?php // RAY_temp_email_validation.php
error_reporting(E_ALL);



// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
function check_valid_email($email)
{
    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    // MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }
    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                       // START REGEX DELIMITER
        . '^'                       // START STRING
        . '[A-Z0-9_-]'              // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'            // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                       // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+' // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                 // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                   // TLD LENGTH >= 2 AND =< 6
        . '$'                       // ENDOF STRING
        . '/'                       // ENDOF REGEX DELIMITER
        . 'i'                       // CASE INSENSITIVE
        ;
        if (!preg_match($regex, $email)) return FALSE;
    }

    // FILTER or PREG DOES NOT TEST IF THE DOMAIN OF THE EMAIL ADDRESS IS ROUTABLE
    $domain = explode('@', $email);
    if ( checkdnsrr($domain[1],"MX") || checkdnsrr($domain[1],"A") ) return TRUE;

    // EMAIL NOT ROUTABLE
    return FALSE;
}




// DEMONSTRATE THE FUNCTION IN ACTION
$e = '';
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    } else
    {
        echo "<br/>BOGUS: $e \n";
    }
}
// END OF PHP - PUT UP THE FORM
?>
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="<?php echo $e; ?>" />
<input type="submit" />
</form>

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 25

Expert Comment

by:madunix
ID: 33725183
Validate an E-Mail Address with PHP, the Right Way...
look @ http://www.linuxjournal.com/article/9585
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 33725343
A quote from the comments on http://www.linuxjournal.com/article/9585 (PHP has changed a bit since 2007, eh?)

"I can't believe LJ have allowed this article to remain here uncorrected for so long."

That is why I test my code before posting it here.  The code snippet at 33725110 is fully functional and self-contained.  You can install it and run it to see the moving parts.

best to all, ~Ray
0
 
LVL 1

Expert Comment

by:ahmad_alinat
ID: 33736265
php has its built in function to validate email:
http://php.net/manual/en/function.filter-var.php
<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
?>

Open in new window

0
 

Author Comment

by:faithless1
ID: 33762899
Ray, can you please include command line usage? I have a txt file that i'm looking to enter as input.thanks.
0
 
LVL 12

Expert Comment

by:Rant32
ID: 33763703
I don't know if filter_var is any better, but trying to validate email addresses with regex is an excercise in futility. Those expressions would lock out my.address+EE.com@gmail.com and hostmaster@com ...

Those are perfectly valid email addresses, you know... Especially the '+' character... You have any idea how annoying it is to have some web form tell you you can't use it, even if it's perfectly valid (everything after + should be ignored for the local part).

You. Can't. Catch. RFC5322. In a regular expression.
0

Featured Post

Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question