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
Solved

Email Validation

Posted on 2010-09-21
8
783 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
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 109

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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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 109

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

856 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