Solved

Email Validation

Posted on 2010-09-21
8
782 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

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 …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
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 count occurrences of each item in an array.

770 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